如何使用自定义类文件对象作为子进程 stdout/stderr? [英] How to use a custom file-like object as subprocess stdout/stderr?

查看:29
本文介绍了如何使用自定义类文件对象作为子进程 stdout/stderr?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

考虑这段代码,其中生成了一个 subprocess.Popen.我想写入子进程的 stdoutstderr 以转到我的自定义文件对象的 .write() 方法,但这不是不是这样.

Consider this code, where a subprocess.Popen is spawned. I'd like writes to the subprocess' stdout and stderr to go to my custom file-object's .write() method, however this isn't the case.

import subprocess

class Printer:

    def __init__(self):
        pass

    def write(self, chunk):
        print('Writing:', chunk)

    def fileno(self):
        return 0

    def close(self):
        return

proc = subprocess.Popen(['bash', '-c', 'echo Testing'], 
                        stdout=Printer(),
                        stderr=subprocess.STDOUT)
proc.wait()

为什么不使用.write()方法,在这种情况下指定stdout=参数有什么用?

Why is the .write() method not used, and what is the use of specifying a stdout= parameter in this case?

推荐答案

根据 文档:

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

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

使用subprocess.PIPE:

proc = subprocess.Popen(['bash', '-c', 'echo Testing'], 
                        stdout=subprocess.PIPE,
                        stderr=subprocess.STDOUT)
print('Writing:', proc.stdout.read())
# OR  print('Writing:', proc.stdout.read().decode())

这篇关于如何使用自定义类文件对象作为子进程 stdout/stderr?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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