【问题标题】:How to use a custom file-like object as subprocess stdout/stderr?如何使用自定义类文件对象作为子进程 stdout/stderr?
【发布时间】:2014-01-28 21:12:36
【问题描述】:

考虑这段代码,其中产生了subprocess.Popen。我想写入子进程的stdoutstderr 以转到我的自定义文件对象的.write() 方法,但事实并非如此。

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=参数有什么用?

【问题讨论】:

标签: python subprocess


【解决方案1】:

根据the documentation

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

使用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())

【讨论】:

  • 这行得通,但是我需要 stdoutstderr 分开(应该有问题),而且是实时的。还有,为什么我的例子不起作用,不是文件类对象吗?
  • @minerz029,正如我引用的文档,subprocess.Popen 不接受类似文件的对象,而只接受PIPEDEVNULL,一个文件描述符,一个文件对象,None .
  • @minerz029, for line in proc.stdout: print('Writing', line.decode())
  • @minerz029,如果你打算写入标准输出,fileno 的返回值应该是1。即使您更改为1,也不会调用write 方法。它只是写入当前进程的标准输出。
  • 感谢该链接,它看起来非常有用。
【解决方案2】:

不直接。也许某些未来版本的 Python 将支持将类似文件的对象转换为某种自动填充管道,但关键是子进程需要访问它可以读取的文件句柄,而无需以某种方式调用 Python 代码。这意味着它需要在操作系统级别上工作,这意味着它仅限于几种可能性:

  • 从父进程继承标准输入(stdin=None 时发生)
  • 从文件中获取输入(当stdin 是文件或整数文件句柄时发生)
  • 从管道获取输入(stdin=subprocess.PIPE 时发生)

使用类似文件的对象意味着您必须自己读取数据,然后通过管道输入数据。

例如:

proc = subprocess.Popen(['sha256sum', '-'], stdin=subprocess.PIPE)
while True:
    chunk = filelike.read(BLOCK_SIZE)
    proc.stdin.write(chunk)
    if len(chunk) < BLOCK_SIZE:
        break
proc.wait()

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2012-07-14
    • 2023-04-06
    • 2015-08-18
    • 1970-01-01
    • 1970-01-01
    • 2017-05-08
    • 2019-04-12
    相关资源
    最近更新 更多