how do i test subprocess's stdout, stderr in python on windows

1.6k views Asked by At
>>> import subprocess
>>> f = open('txt', 'w+')
>>> p = subprocess.Popen(['dir'],stdout=f,stderr=f, shell=True)
>>> p.communicate()
(None, None) # stdout, stderr are empty. Same happens if I open a win32 gui app instead of python (don't think win32 gui apps set a stdout/stderr)

I want to retrieve the stdout or stderr of a subprocess to test a few characteristics of them (not the current sys.__stdout__). How can I do this from the python interpreter?

2

There are 2 answers

3
nu11p01n73R On BEST ANSWER

I think you are looking for subprocess.PIPE

Example

>>> from subprocess import Popen, PIPE
>>> process = subprocess.Popen(['ls'], stdout = PIPE, stderr = PIPE, shell = True )
>>> process.communicate()
('file\nfile1\nfile2, '')

As it can be seen,

process.communicate()[0]

is the stdout of the command and

process.communicate()[1] 

is the stderr

1
Padraic Cunningham On

You can use check_output and catch a CalledProcessError:

from subprocess import check_output, CalledProcessError

try:
    out = check_output(["dir"]) # windows  out = check_output(["cmd", "/c", "dir"])
except CalledProcessError as e:
    out = e.output

print(out)