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中从Azure BLOB存储中读取文件 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- 包装空间模型 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 求两个直方图的卷积 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01