Merging a Python script#39;s subprocess#39; stdout and stderr while keeping them distinguishable(合并 Python 脚本的子进程的 stdout 和 stderr,同时保持它们可区分)
问题描述
我想将 python 脚本的子进程的标准输出和标准输入定向到同一个文件中.我不知道如何使两个来源的线条可区分?(例如,在 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 是一个特殊的标志告诉 subprocess 将所有 stderr 输出路由到 stdout,从而组合您的两个流.
subprocess.STDOUT is a special flag that tells subprocess to route all stderr output to stdout, thus combining your two streams.
顺便说一句,select 在 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,同时保持它们可区分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:合并 Python 脚本的子进程的 stdout 和 stderr,同时保持它们可区分
基础教程推荐
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
