2014-11-05 2 views
0

다음 코드를 사용하여 인쇄 문을 텍스트 파일로 리디렉션합니다.하위 프로세스에서 인쇄를 로그 파일로 리디렉션

old_stdout = sys.stdout 
log_file = open("message.log","w") 
sys.stdout = log_file 
print "this will be written to message.log" 

subprocess.call("iPython.exe", "script.py") #subprocesses here take this form 

sys.stdout = old_stdout 
log_file.close() 

내 문제는이 방법이 하위 프로세스에는 적용되지 않는 것입니다. "script.py"의 print 문은 "message.log"에 나타나지 않습니다. 그들이 그렇게 할 수 있도록 어떻게 만들 수 있습니까?

+0

더 나은 옵션 일 수있는 로깅을위한 특정 라이브러리가 있습니다 - https://docs.python.org/2/library/logging.html – thefragileomen

답변

1

subprocess.call 대신 subprocess.Popen을 사용하면 stdoutstderr을 리디렉션 할 수 있습니다.

import subprocess 

with (open('message_stdout.log', 'w'), open('message_stderr.log', 'w')) as (stdout_file, stderr_file): 
    my_process = subprocess.Popen(["iPython.exe", "script.py"], 
            stdout=stdout_file, 
            stderr=stderr_file) 

또한 script.py의 모든 출력이 하나의 파일로 전송 될 수 있도록,이 같은 표준 출력을 표준 오류를 리디렉션 할 수 있습니다.

import subprocess 

with open('message.log', 'w') as stdout_file: 
    my_process = subprocess.Popen(["iPython.exe", "script.py"], 
            stdout=stdout_file, 
            stderr=subprocess.STDOUT) 

그러나, 또 다른 스크립트를로드 iPython를 호출 뭔가를 subprocessing 것은 일할 수있는 끔찍한 방법입니다. 대신, script.py 모듈을 직접 호출해야합니다.

관련 문제