Search code examples
pythonsubprocesspopen

Python subprocess.Popen strange behavior


I'm trying to run a process and when it's done, read stderr and stdout. I found only way to do this with Python is creating a subprocess.Popen, with subprocess.PIPE as stderr and stdout args, and then reading Popen.stderr and Popen.stdout file descriptors.

In [133]: subprocess.call(['python', '-c', "import sys; sys.exit(1)"])
Out[133]: 1

In [134]: p = subprocess.Popen(['python', '-c', "import sys; sys.exit(1)"])

In [135]: p.returncode

In [136]:

I can get returncode of subprocess.call but I can't get returncode of subprocess.Popen. I've also tried reading stderr to see if subprocess.Popen really runs the command:

In [143]: p = subprocess.Popen(['python', '-c', "import sys; sys.stderr.write('ook'); sys.exit(1)"], stderr=subprocess.PIPE)

In [144]: p.stderr.read()
Out[144]: 'ook'

In [145]: p.returncode

In [146]: p.kill()

In [147]: p.returncode

In [148]: 

So I can read stderr, which means command I give to subprocess.Popen is running, but I can't get returncode of subprocess.Popen. Any ideas?


Solution

  • You have to wait for the command to finish.

    >>> p.wait()
    1
    >>> p.returncode
    1
    

    Or use communicate:

    >>> stdout, stderr = p.communicate()
    >>> stdout
    >>> stderr
    'ook'
    >>> p.returncode
    1