簡體   English   中英

記錄過程的STDIN和STDOUT

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM