0

私のコードの一部:

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ます。どうすればこれを保証できますか?

4

1 に答える 1

3

Subprocessモジュールのドキュメントから:

stdin、stdout、および stderr は、実行されたプログラムの標準入力、標準出力、および標準エラー ファイル ハンドルをそれぞれ指定します。有効な値は、PIPE、既存のファイル記述子 (正の整数)、既存のファイル オブジェクト、および None です。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))
于 2012-10-12T10:04:37.347 に答える