管道输出 subprocess.Popen 到文件 [英] Piping output of subprocess.Popen to files

查看:93
本文介绍了管道输出 subprocess.Popen 到文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 subprocess.Popen 启动多个长时间运行的进程,并且希望从以下位置获得 stdoutstderr每个自动管道到单独的日志文件.每个进程将同时运行几分钟,我希望将两个日志文件(stdoutstderr)每个进程写入作为进程运行.

I need to launch a number of long-running processes with subprocess.Popen, and would like to have the stdout and stderr from each automatically piped to separate log files. Each process will run simultaneously for several minutes, and I want two log files (stdout and stderr) per process to be written to as the processes run.

我是否需要在循环中的每个进程上不断调用 p.communicate() 以更新每个日志文件,或者有什么方法可以调用原始的 Popen 命令以便 stdoutstderr 自动流式传输以打开文件句柄?

Do I need to continually call p.communicate() on each process in a loop in order to update each log file, or is there some way to invoke the original Popen command so that stdout and stderr are automatically streamed to open file handles?

推荐答案

Per 文档,

stdin、stdout 和 stderr 指定执行程序的标准输入,标准输出和标准错误文件句柄,分别.有效的值为 PIPE,一个现有文件描述符(一个正整数),一个现有文件对象,无.

stdin, stdout and stderr specify the executed programs’ standard input, standard output and standard error file handles, respectively. Valid values are PIPE, an existing file descriptor (a positive integer), an existing file object, and None.

所以只需将 open-for-writing 文件对象作为命名参数 stdout=stderr= 传递,你应该没问题!

So just pass the open-for-writing file objects as named arguments stdout= and stderr= and you should be fine!

这篇关于管道输出 subprocess.Popen 到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆