Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/logging/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将打印重定向到子流程中的日志文件_Python_Logging_Subprocess - Fatal编程技术网

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
模块。

有一个特定的日志库,这可能是一个更好的选择-