Piping output of subprocess.Popen to files(subprocess.Popen 的管道输出到文件)
问题描述
我需要使用 subprocess.Popen 启动多个长时间运行的进程,并希望从 stdout 和 stderr每个都自动通过管道传输到单独的日志文件.每个进程将同时运行几分钟,我希望将两个日志文件(stdout 和 stderr)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> 命令,以便 stdout 和 stderr 自动流式传输到打开文件句柄?
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 的管道输出到文件
基础教程推荐
- 在 Celery 工作人员中捕获 Heroku SIGTERM 以优雅地关 2022-01-01
- 将 x 轴刻度更改为自定义字符串 2022-01-01
- 尝试制作WhatsApp机器人 2022-01-01
- numpy float:比算术运算中内置的慢 10 倍? 2022-01-01
- pyserial - 可以从线程 a 写入串行端口,是否阻塞从线程 b 读取? 2022-01-01
- 用 Python 编写 Fortran 无格式文件 2022-01-01
- 使用生成器和迭代器时 Python 多循环失败 2022-01-01
- 与常规 dict 相比,Python manager.dict() 非常慢 2022-01-01
- Discord.py 缺少必需的参数 2022-01-01
- 由Python将MP3转换为MIDI(类型错误:无法加载插件:mtg-Melodia:Melodia) 2022-01-01
