我想用subprocess.Popen()
运行一个进程,并通过python shell与它进行通信,就像subprocess.Popen
通常的行为一样。除此之外,我想讨论将STDIN和STDOUT记录到日志文件中。
我该怎么做?
答案 0 :(得分:1)
假设话语性意味着漫游和漫游意味着所有人都在同一个文件中,那么下面的代码片段就是你所要求的。
通过歧视来源和互动来讨论日志记录
覆盖类似问题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而不是文件,然后继承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)