osa1
osa1

Reputation: 7088

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?

Upvotes: 2

Views: 2244

Answers (3)

01100110
01100110

Reputation: 2354

if (subprocess.call(command, shell=True) != 0):
    # wait and return returncode attribute
    # non-zero returncode indicates failure
    pass 

Upvotes: 0

avasal
avasal

Reputation: 14872

try this:

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

In [40]: p.poll()
Out[40]: 1

Upvotes: 2

Fred Foo
Fred Foo

Reputation: 363817

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

Upvotes: 4

Related Questions