当通过Python调用时,如何确保所有git输出都发送到日志文件?

当通过Python调用时,如何确保所有git输出都发送到日志文件?,python,Python,我的部分代码: 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 subproces

我的部分代码:

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()
当我尝试运行此操作时,我的输出为:

[~/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
目前我并不关心Python错误,但我需要git发送的所有输出进入
每日备份运行.log
——甚至是
致命错误:不是repo
错误。如何确保这一点?

来自模块文档:

stdin、stdout和stderr分别指定执行程序的标准输入、标准输出和标准错误文件句柄。有效值包括管道、现有文件描述符(正整数)、现有文件对象和无。管道指示应创建到子级的新管道

您可以按如下方式修改代码:

# 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))
从模块文档中:

stdin、stdout和stderr分别指定执行程序的标准输入、标准输出和标准错误文件句柄。有效值包括管道、现有文件描述符(正整数)、现有文件对象和无。管道指示应创建到子级的新管道

您可以按如下方式修改代码:

# 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))

谢谢大家!
stderr
成功了!也谢谢你的最后一句话,就像你能读懂我的心思:)谢谢
stderr
成功了!也谢谢你的最后一句话,好像你能读懂我的心思:)