簡體   English   中英

通過Python調用時,如何確保所有git輸出都發送到日志文件?

[英]How do I ensure all git output is sent to a log file when called via 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 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發送的所有輸出都進入daily_backup_run.log甚至是fatal: Not a repo錯誤。 我該如何確保?

子過程模塊文檔中:

stdin,stdout和stderr分別指定執行程序的標准輸入,標准輸出和標准錯誤文件句柄。 有效值為PIPE,現有文件描述符(正整數),現有文件對象和無。 PIPE指示應創​​建到子級的新管道。

您可以按以下方式修改代碼:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM