Answer a question

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

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

Answers

According to the documentation:

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.

Using 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())
Logo

Python社区为您提供最前沿的新闻资讯和知识内容

更多推荐