将打印重定向到子流程中的日志文件

2024-04-23 08:47:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用以下代码将print语句重定向到文本文件中。你知道吗

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()

我的问题是,这似乎不适用于子流程。“中的打印语句”脚本.py“不会出现在”消息.log". 我怎样才能让他们这么做?你知道吗


Tags: 代码pylogmessagestdoutsys语句open
1条回答
网友
1楼 · 发布于 2024-04-23 08:47:52

使用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模块。你知道吗

相关问题 更多 >