sashoalm
sashoalm

Reputation: 79467

Can't read stderr from subprocess.Popen

I want to start a child process and read its stderr, but so far, I can't read anything at all using subprocess.Popen, even stdout. I'm trying to use subprocess.communicate() to read from stdout and stderr. This is what I do:

import subprocess
p = subprocess.Popen('ls')
s = p.communicate()
print s

This gives me output (None, None). I think the pair is for stdin and stderr. Is that the case? Anyway, how can I read stdout and stderr from a process started with subprocess.Popen?

Upvotes: 3

Views: 3292

Answers (2)

joaquin
joaquin

Reputation: 85613

From Python docs (Subprocess module):

Popen.communicate(input=None) 

Interact with process: Send data to stdin. Read data from stdout and stderr, until end-of-file is reached. Wait for process to terminate. The optional input argument should be a string to be sent to the child process, or None, if no data should be sent to the child.

communicate() returns a tuple (stdoutdata, stderrdata).

Note that if you want to send data to the process’s stdin, you need to create the Popen object with stdin=PIPE. Similarly, to get anything other than None in the result tuple, you need to give stdout=PIPE and/or stderr=PIPE too.

Upvotes: 1

jamesls
jamesls

Reputation: 5608

You need to specify the stdout=subprocess.PIPE and stderr=subprocess.PIPE when you create your Popen object:

  p = subprocess.Popen('ls', stdout=subprocess.PIPE, stderr=subprocess.PIPE)

Upvotes: 4

Related Questions