'Configure GitPython to output/log commands and process output

I'm using GitPython to run several simple commands against repos. Essentially most of it is just:

repo = Repo(repo_dir)
repo.git.fetch()
result = repo.git.diff("origin", name_only=True)
repo.git.merge()
# ...

Is there some way to setup GitPython to output/log the commands that are run, and also display the raw output they produce?

For example, the above I would expect to be something along the lines of:

$ git fetch
$ git diff --name-only origin
path/to/differing_file
path/to/another/differing_file
$ git merge


Solution 1:[1]

GitPython uses the module logging. By adding logging.basicConfig(level=logging.DEBUG) before your code, it prints logs like

DEBUG:git.cmd:Popen(['git', 'fetch'], cwd=E:\path\foo, universal_newlines=False, shell=None)

If you want it to print formatted logs as you expect, you could modify GitPython's source code. I'm using Python 2.7 and my GitPython is installed at C:\Python27\lib\site-packages\git. You can run git.__file__ in REPL to find your installation directory. In the file C:\Python27\lib\site-packages\git\cmd.py, you can find a method def execute. It calls subprocess.Popen to run the command. You can modify the line log.debug before Popen or just insert print(' '.join(cmd)) at a proper line. If you are using Python 3.3 or newer, you could also refer to this answer on how to print the command with subprocess.

Solution 2:[2]

You could also:

pull = self.repo.git.pull('--rebase')
log.info(pull)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 Oweis Al-Agtash