合并 Python 脚本的子进程的 stdout 和 stderr,同时保持它们可区分

2023-07-22Python开发问题
32

本文介绍了合并 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,同时保持它们可区分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

The End

相关推荐

在xarray中按单个维度的多个坐标分组
groupby multiple coords along a single dimension in xarray(在xarray中按单个维度的多个坐标分组)...
2024-08-22 Python开发问题
15

Pandas中的GROUP BY AND SUM不丢失列
Group by and Sum in Pandas without losing columns(Pandas中的GROUP BY AND SUM不丢失列)...
2024-08-22 Python开发问题
17

GROUP BY+新列+基于条件的前一行抓取值
Group by + New Column + Grab value former row based on conditionals(GROUP BY+新列+基于条件的前一行抓取值)...
2024-08-22 Python开发问题
18

PANDA中的Groupby算法和插值算法
Groupby and interpolate in Pandas(PANDA中的Groupby算法和插值算法)...
2024-08-22 Python开发问题
11

PANAS-基于列对行进行分组,并将NaN替换为非空值
Pandas - Group Rows based on a column and replace NaN with non-null values(PANAS-基于列对行进行分组,并将NaN替换为非空值)...
2024-08-22 Python开发问题
10

按10分钟间隔对 pandas 数据帧进行分组
Grouping pandas DataFrame by 10 minute intervals(按10分钟间隔对 pandas 数据帧进行分组)...
2024-08-22 Python开发问题
11