subprocess.Popen 的管道输出到文件

Piping output of subprocess.Popen to files(subprocess.Popen 的管道输出到文件)

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

问题描述

我需要使用 subprocess.Popen 启动多个长时间运行的进程,并希望从 stdoutstderr每个都自动通过管道传输到单独的日志文件.每个进程将同时运行几分钟,我希望将两个日志文件(stdoutstderr)per process 作为进程写入运行.

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() 以更新每个日志文件,或者有什么方法可以调用原始 Popencode> 命令,以便 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?

推荐答案

根据 文档,

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.

所以只需将可写入的文件对象作为命名参数 stdout=stderr= 传递就可以了!

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

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

本文标题为:subprocess.Popen 的管道输出到文件

基础教程推荐