[英]Logging Process' STDIN and STDOUT
我想使用subprocess.Popen()
运行一个进程,并通过python shell与之通信,就像subprocess.Popen
通常行为一样。 除此之外,我想将STDIN和STDOUT谨慎地记录到日志文件中。
我该怎么做?
假设话语意味着漫游,而漫游则意味着都在同一个文件中,那么下面的代码段就是您所要求的。
辨别来源和交互作用的话语日志
像这里类似的问题一样覆盖其通信方法
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代替文件,然后使用StringIO子类重写其write方法以打开添加时间戳和源的方法。 然后编写一个自定义的比较函数,该函数根据时间戳和源进行排序,首先是时间戳,然后是源输入,然后是输出
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("file.log","wb") as in logfile:
subprocess.Popen(cmd, shell=True, universal_newlines = True, stdin=logfile, stdout=logfile)
相反如下所示
草书
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)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.