Python 2.2 はかなり古いです。subprocessは とよりもはるかに優れているため、可能であればアップグレードする必要がos.systemありos.popenます。
必要なのは、文字列への書き込みとstdout文字列へのキャプチャの両方を行うファイルのようなオブジェクトです (おそらく を使用します。その後、呼び出しでそのオブジェクトをおよびStringIO)として指定できます。stdoutstderrsubprocess
import sys, subprocess
from cStringIO import StringIO
class Outcap(object):
def __init__(self):
self.output = StringIO()
def write(self, data):
sys.stdout.write(data)
self.output.write(data)
def flush(self):
sys.stdout.flush(data)
def close(self):
pass
@property
def text(self):
return self.output.getvalue()
outcap = Outcap()
try:
subprocess.check_call("foo bar baz".split(), stdout=outcap, stderr=outcap)
subprocess.check_call("one two three".split(), stdout=outcap, stderr=outcap)
except CalledProcessError as e:
outcap.write("return code: %s\n", e.returncode)
open("log.txt", "w").write(outcap.text)
Python をアップグレードできないが、Linux を使用している場合、別のオプションは、実行中のコマンドを command でパイプ処理することにより、Python の外部で処理することですtee。
your command goes here 2>&1 | tee log.txt
これにより、コマンドのすべての出力が保存さlog.txtれ、標準出力に送信されます。そこから何をするかは、Python スクリプト次第です。たとえば、コマンドの 1 つが失敗した場合にのみ、一時ファイルにログを記録し、それを永続的な場所に移動することができます。