0

Part of my code:

import subprocess
import logging
logging.basicConfig(filename='daily_backup_run.log', level=logging.DEBUG)

try:
  git_command = subprocess.Popen("git status", shell="true")
  git_status_output = git_command.stdout.readline()
except subprocess.CalledProcessError, e:
  git_status_output = e.output
logging.debug(' Output of git status: ' + git_status_output)
exit()

When I attempt to run this, my output is:

[~/experiment_folder]# python git.py
Traceback (most recent call last):
  File "git.py", line 35, in ?
    except subprocess.CalledProcessError, e:
AttributeError: 'module' object has no attribute 'CalledProcessError'
fatal: Not a git repository (or any of the parent directories): .git

I am not concerned with the Python errors at the moment, but I need all output sent by git to go into the daily_backup_run.log - even the fatal: Not a repo error. How do I ensure this?

1 Answer 1

3

From the Subprocess module documentation:

stdin, stdout and stderr specify the executed program’s standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None. PIPE indicates that a new pipe to the child should be created.

You can modify the code as follows:

# working dir in which git [command] is called
cwd = '/path/to/git/repository' 

p = subprocess.Popen("git status", shell="true", cwd=cwd,
                     stdout=subprocess.PIPE, stderr=subprocess.PIPE)
outdata, errdata = p.communicate()

logging.debug('Output of git status: {}. Error data if any: {}'
              .format(outdata, errdata))
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you! stderr did the trick! Thank you also for the last line, its like you can read my mind :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.