Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use a custom file-like object as subprocess stdout/stderr?

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?

like image 987
kiri Avatar asked Jan 10 '14 02:01

kiri


1 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())
like image 146
falsetru Avatar answered Nov 08 '22 12:11

falsetru