python - 如何为 subprocess.call 创建自定义输出流

标签 python python-3.x io subprocess

我试图通过定义自己的输出流来获取 subprocess.call 的实时输出,但它似乎不起作用。

原因:我想运行一个子进程并获取对 stdout 的调用的输出(实时以便我可以查看脚本并查看当前进度)并将其记录到文件中

子进程.py:

import time

while True:
    print("Things")
    time.sleep(1)

主进程.py

import subprocess
import io

class CustomIO(io.IOBase):
    def write(self, str):
        print("CustomIO: %s"%str)
        # logging to be implemented here

customio = CustomIO()
subprocess.call(["python3", "print_process.py"], stdout=customio)

但是当我运行此代码时,我收到此错误消息:

Traceback (most recent call last):                                   
    File "call_test.py", line 9, in <module>                           
        subprocess.call(["python3", "print_process.py"], stdout=customio)
    File "/usr/lib/python3.4/subprocess.py", line 537, in call         
        with Popen(*popenargs, **kwargs) as p:                           
    File "/usr/lib/python3.4/subprocess.py", line 823, in __init__     
        errread, errwrite) = self._get_handles(stdin, stdout, stderr)    
    File "/usr/lib/python3.4/subprocess.py", line 1302, in _get_handles
        c2pwrite = stdout.fileno()                                       
io.UnsupportedOperation: fileno

那么,有人知道这是否可能吗?

我继承了错误的基类吗?

我没有重载正确的方法吗?

或者我是否完全偏离了轨道,应该以完全不同的方式来解决这个问题?

最佳答案

如果要处理子进程的输出,则需要传递stdout=subprocess.PIPE。但是,call()run() 都会等到进程完成后才使其可用,因此您无法使用这些函数实时处理它。

您需要使用subprocess.Popen:

import subprocess as sp

def handle_output(output_line):
    ...

my_process = sp.Popen(["python3", "print_process.py"],
                      stdout=sp.PIPE,
                      universal_newlines=True) # changes stdout from bytes to text

for line in my_process.stdout:
    handle_output(line)

my_process.wait()

更新:确保刷新子进程中的输出缓冲区:

while True:
    print("Things", flush=True)
    time.sleep(1)

关于python - 如何为 subprocess.call 创建自定义输出流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46201419/

相关文章:

python/numpy 生成二进制文件以供 C 读取

python - 将 TIFF 转换为 numpy 数组

python - 处理 [Errno 111] 连接被 flask 中的请求拒绝返回

python - 优化: Search the best way to compare two list of dict (Python)

python - pandas 创建一个列并从字典中为其赋值

python - 如何在 tkinter 中向从 csv 读取的表格的每一行添加复选按钮?

python - django2 + python3 : TemplateDoesNotExist

java - 针对 IO BufferInputStream 的 Nio 字节缓冲区(按 channel )

c# - 有没有办法在 .NET 中执行零复制?

python - 将数据扩展到新列进行分组