2012-02-14 4 views
1

subprocess.Popen()으로 프로세스를 실행하고 일반적인 동작 인 subprocess.Popen처럼 파이썬 쉘을 통해 프로세스와 통신하고 싶습니다. 그 외에도 STDIN 및 STDOUT을 논리적으로 로그 파일에 기록하고 싶습니다.로깅 프로세스 'STDIN and 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를 서브 클래스 화하여 쓰기 메소드를 다음으로 대체하십시오. 타임 스탬프와 소스를 추가합니다. 그런 다음 사용자가 제 소인 및 소스, 타임 스탬프에 기초하여 정렬합니다 기능하고 소스 입력하고 출력

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) 
+0

어쩌면 나는 충분히 명확하지 않았을 것입니다. 저는 서브 프로세스와 같은 파이썬 셸을 통해 프로세스와 통신하고 싶습니다. 일반적인 동작을 엽니 다. 그 외에도 STDIN 및 STDOUT을 로그 파일에 기록하고 싶습니다. – iTayb

+0

입력은 예제의 파일에서 가져온 것입니다 ... 표준 입력 인터페이스를 사용하여 프로세스를 제어하려고합니다. 나는 또한 출력을 파이썬 셸에 표시하려고합니다. 유일한 차이점은이 모든 입출력 트래픽을 기록하려고한다는 것입니다. – iTayb

관련 문제