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?
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())
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With