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


大气响应式网络建站服务公司织梦模板
高端大气html5设计公司网站源码
织梦dede网页模板下载素材销售下载站平台(带会员中心带筛选)
财税代理公司注册代理记账网站织梦模板(带手机端)
成人高考自考在职研究生教育机构网站源码(带手机端)
高端HTML5响应式企业集团通用类网站织梦模板(自适应手机端)