2012-02-14 13 views
1

subprocess.Popen()でプロセスを実行し、subprocess.PopenのようなPythonシェルを使用して通信したいと考えています。それに加えて、STDINとSTDOUTをログファイルに対話的に記録したいと思います。ログプロセス 'STDINとSTDOUT

どうすればいいですか?

+0

あなたは散漫に何を意味しますか?あなたは両方が同じファイルにログすることを意味しますか? – Appleman1234

+0

はい、STDINの後ろにSTDOUTを追加するだけではありません。私はそれを口頭で必要とするので、どんな入力がどの出力をもたらしたかを知ることができます。 – iTayb

答えて

1

散発的には、同じファイル内に散歩と散歩があることを意味すると仮定すると、次のスニペットが要求したものです。

源の識別と相互作用言説ロギング

ソース

まず利用たStringIOの識別と同様の質問のようhere

import subprocess 

def logcommunicate(self, s): 
    self.logfilehandle.write("Input "+s) 
    std = self.oldcommunicate(s) 

    self.logfilehandle.write("Output "+std[0]) 
    return std 

subprocess.Popen.oldcommunicate = subprocess.Popen.communicate 
subprocess.Popen.communicate = logcommunicate 
logfh = open("/tmp/communicate.log", "a") 

proc = subprocess.Popen(['cat'], stdin=subprocess.PIPE, stdout=subprocess.PIPE) 
proc.logfilehandle = logfh 

result = proc.communicate("hello there\n") 
print result 

言説ロギングをその通信メソッドをオーバーライド

ファイルの代わりにStringIOをサブクラス化してwriteメソッドをオーバーライドするタイムスタンプとソースを追加します。次いで、書き込み

with open("file.log","wb") as in logfile: 
subprocess.Popen(cmd, shell=True, universal_newlines = True, stdin=logfile, stdout=logfile) 

カスタム比較タイムスタンプとソースに基づいてソートする機能、タイムスタンプ第一及び、ソース入力と、出力

with open("file.log","wb") as in logfile: 
out = MyOutPutStringIO.StringIO() 
in = MyInputStringIO.StringIO() 
subprocess.Popen(cmd, shell=True, universal_newlines = True, stdin=in, stdout=out) 

#Then after you are done 
linestotal = [] 
for line in in.readlines(): 
    linestotal.append(line) 
for line in out.readlines(): 
    linestotal.append(line) 

linestotal.sort(customsortbasedontimestampandinput) 

for line in linestotal.readlines(): 
    logwrite.write(line) 

言説ロギングは、反対が

以下に示します。 筆記体ロギング

with open("stdout.txt","wb") as out: 
with open("stderr.txt","wb") as err: 
with open("stdin.txt","wb") as in: 
subprocess.Popen(cmd, shell=True, universal_newlines = True, stdin=in,stdout=out,stderr=err) 
+0

多分私は十分に明確ではありませんでした - 私はサブプロセスのように、Pythonシェルを介してプロセスと通信したいと思います。それに加えて、STDINとSTDOUTをログファイルに記録したいと思います。 – iTayb

+0

入力はあなたの例のファイルから来ています...私は標準入力インターフェースでプロセスを制御したいと思います。私はまた、出力をpythonシェルに表示したい。唯一の違いは、このすべての入出力トラフィックをログに記録することです。 – iTayb

関連する問題