2014-11-05 89 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」中的打印語句不會出現在「message.log」中。我該如何做到這一點?

+0

有一個特定的日誌記錄庫可能是更好的選擇 - https://docs.python.org/2/library/logging.html – thefragileomen 2014-11-05 03:01:55

回答

1

使用subprocess.Popen而不是subprocess.call,它允許您重定向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) 

您也可以將stderr重定向到stdout這樣,這樣從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加載另一個腳本是工作一個可怕的方式。相反,你應該直接調用script.py模塊。

相關問題