Take the 2-minute tour ×

I am having problems to retrieve the following information of a git repo using python:

  1. I would like to get a list of all tags of this repository.
  2. I would like to checkout another branch and also create a new branch for staging.
  3. I would like to tag a commit with an annotated tag.

I have looked into the dulwich's documentation and the way it works seems very bare-bones. Are there also alternatives which are easier to use?

share|improve this question

2 Answers 2

up vote 2 down vote accepted

The simplest way to get all tags using Dulwich is:

from dulwich.repo import Repo
r = Repo("/path/to/repo")
tags = r.refs.as_dict("refs/tags")

tags is now a dictionary mapping tags to commit SHA1s.

Checking out another branch:

r.refs.set_symbolic_ref("HEAD", "refs/heads/foo")

Creating a branch:

r.refs["refs/heads/foo"] = head_sha1_of_new_branch
share|improve this answer

Call git via subprocess. From one of my own programs:

def gitcmd(cmds, output=False):
    """Run the specified git command.

    cmds   -- command string or list of strings of command and arguments
    output -- wether the output should be captured and returned, or
              just the return value
    if isinstance(cmds, str):
        if ' ' in cmds:
            raise ValueError('No spaces in single command allowed.')
        cmds = [cmds] # make it into a list.
    # at this point we'll assume cmds was a list.
    cmds = ['git'] + cmds # prepend with git
    if output: # should the output be captured?
        rv = subprocess.check_output(cmds, stderr=subprocess.STDOUT).decode()
        with open(os.devnull, 'w') as bb:
            rv = subprocess.call(cmds, stdout=bb, stderr=bb)
    return rv

Some examples:

rv = gitcmd(['gc', '--auto', '--quiet',])
outp = gitcmd('status', True)
share|improve this answer

Your Answer


