简体   繁体   English

记录过程的STDIN和STDOUT

[英]Logging Process' STDIN and STDOUT

I would like to run a process with subprocess.Popen() and communicate with it through the python shell, like the subprocess.Popen usual behavior. 我想使用subprocess.Popen()运行一个进程,并通过python shell与之通信,就像subprocess.Popen通常行为一样。 Beside that, I would like to discursively log the STDIN and STDOUT to a logfile. 除此之外,我想将STDIN和STDOUT谨慎地记录到日志文件中。

How can I do it? 我该怎么做?

Assuming discursively means rambling and rambling means all in the same file, then the following snippet is what you requested. 假设话语意味着漫游,而漫游则意味着都在同一个文件中,那么下面的代码段就是您所要求的。

Discursive logging with discrimination of the source and interaction 辨别来源和交互作用的话语日志

Override its communicate method like similar question 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 

Discursive logging with discrimination of the source 带有源判别的话语记录

First use StringIO instead of files, then subclass StringIO to override its write method to open that appends timestamp and source. 首先使用StringIO代替文件,然后使用StringIO子类重写其write方法以打开添加时间戳和源的方法。 Then write a custom compare function that sorts based on timestamp and source, timestamp first and then source Input and then output 然后编写一个自定义的比较函数,该函数根据时间戳和源进行排序,首先是时间戳,然后是源输入,然后是输出

 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)

Discursive logging 话语日志

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

The opposite is shown below 相反如下所示

Cursive logging 草书

 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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM