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?


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

尝试这个:

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

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

if (subprocess.call(command, shell=True) != 0):
    # wait and return returncode attribute
    # non-zero returncode indicates failure
    pass 
链接地址: http://www.djcxy.com/p/77136.html

上一篇: 管道输出时,Python子流程会作为Popen挂起

下一篇: Python子进程。打开奇怪的行为