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 的管道输出到文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

Leetcode 234: Palindrome LinkedList(Leetcode 234:回文链接列表)
How do I read an Excel file directly from Dropbox#39;s API using pandas.read_excel()?(如何使用PANDAS.READ_EXCEL()直接从Dropbox的API读取Excel文件?)
subprocess.Popen tries to write to nonexistent pipe(子进程。打开尝试写入不存在的管道)
I want to realize Popen-code from Windows to Linux:(我想实现从Windows到Linux的POpen-code:)
Reading stdout from a subprocess in real time(实时读取子进程中的标准输出)
How to call type safely on a random file in Python?(如何在Python中安全地调用随机文件上的类型?)