How to determine subprocess.Popen() failed when sh

2019-02-21 20:45发布

Windows version of Python 2.6.4: Is there any way to determine if subprocess.Popen() fails when using shell=True?

Popen() successfully fails when shell=False

>>> import subprocess
>>> p = subprocess.Popen( 'Nonsense.application', shell=False )
Traceback (most recent call last):
  File ">>> pyshell#258", line 1, in <module>
    p = subprocess.Popen( 'Nonsense.application' )
  File "C:\Python26\lib\subprocess.py", line 621, in __init__
    errread, errwrite)
  File "C:\Python26\lib\subprocess.py", line 830, in
_execute_child
    startupinfo)
WindowsError: [Error 2] The system cannot find the file specified

But when shell=True, there appears to be no way to determine if a Popen() call was successful or not.

>>> p = subprocess.Popen( 'Nonsense.application', shell=True )
>>> p
>>> subprocess.Popen object at 0x0275FF90>>>
>>> p.pid
6620
>>> p.returncode
>>>

Ideas appreciated.

Regards, Malcolm

2条回答
贪生不怕死
2楼-- · 2019-02-21 21:02

In the first case it fails to start, in the second - it successfully starts shell which, in turn, fails to execute the application. So your process has been properly spawned, exited and waits for you to inquire about its exit code. So, the thing is, unless your shell or environment (e.g. no memory) is utterly broken there's no way Popen itself may fail.

So, you can safely .poll() and .wait() on it to get all the sad news.

查看更多
We Are One
3楼-- · 2019-02-21 21:09

returncode will work, although it will be None until you've called p.poll(). poll() itself will return the error code, so you can just do

if a.poll() != 0:
    print ":("
查看更多
登录 后发表回答