问题描述
我想将 python 脚本的子进程的 stdout 和 stdin 定向到同一个文件中.我不知道的是如何使来自两个来源的线条可区分?(例如,在 stderr 的行前加上感叹号.)
I would like to direct a python script's subprocess' stdout and stdin into the same file. What I don't know is how to make the lines from the two sources distinguishable? (For example prefix the lines from stderr with an exclamation mark.)
在我的特殊情况下,不需要实时监控子进程,正在执行的 Python 脚本可以等待其执行结束.
In my particular case there is no need for live monitoring of the subprocess, the executing Python script can wait for the end of its execution.
推荐答案
tsk = subprocess.Popen(args,stdout=subprocess.PIPE,stderr=subprocess.STDOUT)
subprocess.STDOUT
是一个特殊标志,用于告诉子进程将所有 stderr 输出路由到 stdout,从而合并您的两个流.
subprocess.STDOUT
is a special flag that tells subprocess to route all stderr output to stdout, thus combining your two streams.
顺便说一句,选择在 Windows 中没有 poll().subprocess 只使用文件句柄号,不会调用你的文件输出对象的 write 方法.
btw, select doesn't have a poll() in windows. subprocess only uses the file handle number, and doesn't call your file output object's write method.
要捕获输出,请执行以下操作:
to capture the output, do something like:
logfile = open(logfilename, 'w')
while tsk.poll() is None:
line = tsk.stdout.readline()
logfile.write(line)
这篇关于合并 Python 脚本的子进程的 stdout 和 stderr,同时保持它们的可区分性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!