Python 将打印重定向到子流程中的日志文件
我使用以下代码将打印语句重定向到文本文件中Python 将打印重定向到子流程中的日志文件,python,logging,subprocess,Python,Logging,Subprocess,我使用以下代码将打印语句重定向到文本文件中 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
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”中。我怎样才能让他们这样做呢?使用
subprocess.Popen
而不是subprocess.call
,这允许您重定向stdout
和stderr
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
模块。有一个特定的日志库,这可能是一个更好的选择-