Search code examples
pythonpython-3.xgitsubprocessgit-fetch

Getting git fetch output to file through python


I am trying to save git fetch output to file through python, using:

subprocess.check_output(["git", "fetch", "origin", ">>", "C:/bitbucket_backup/backup.log", "2>&1"], cwd='C:/bitbucket_backup/loopx')

but I believe there is something missing in subprocess.check_output args because when adding >> C:/bitbucket_backup/backup.log 2>&1 I receive this error:

Traceback (most recent call last):
  File "<pyshell#28>", line 1, in <module>
     subprocess.check_output(["git", "fetch", "origin", ">>", "C://bitbucket_backup//backup.log", "2>&1"], cwd='C://bitbucket_backup//loopx')
  File "C:\Users\fabio\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 336, in check_output
     **kwargs).stdout
  File "C:\Users\fabio\AppData\Local\Programs\Python\Python36-32\lib\subprocess.py", line 418, in run
     output=stdout, stderr=stderr)
subprocess.CalledProcessError: Command '['git', 'fetch', 'origin', '>>', 'C://bitbucket_backup//backup.log', '2>&1']' returned non-zero exit status 128.

Solution

  • Quickfix: enable shell features to handle redirection arguments:

    subprocess.check_output(["git", "fetch", "origin", ">>", "C:/bitbucket_backup/backup.log", "2>&1"], cwd='C:/bitbucket_backup/loopx', shell=True)
    

    But that's really dirty as python is able to do that really nicely:

    output = subprocess.check_output(["git", "fetch", "origin"], stderr=subprocess.STDOUT, cwd='C:/bitbucket_backup/loopx')
    with open("C:/bitbucket_backup/backup.log","ab") as f:  # append to file
        f.write(output)
    

    That said, if you're to rewrite all git commands in python, maybe you should use a git python API like GitPython for instance.