Discovering git branch from python script

Viewed 38

I have a python script. I need to access the name of the git branch from which I'm running the python script, through python, during runtime. Is there a way to do this?

Edit: os.system("git rev-parse --abbrev-ref HEAD") outputs to the cli, I don't see how I would get access to it from python...

I would like to have sth like git_branch = <python commands>

1 Answers

You could use GitPython, something like the following:

>>> import git
>>> import os
>>> git_branch = git.Repo(os.getcwd()).active_branch.name
>>> git_branch
'master'

Otherwise, as already pointed out by Yevhen Kuzmovych in the comments, you could use PyGit.

Related