当shell = True时,如何确定subprocess.Popen()失败

时间:2010-05-18 22:19:13

标签: python subprocess popen

Windows 2.6 of Python 2.6.4:有没有办法确定使用shell = True时subprocess.Popen()是否失败?

当shell = False时,Popen()成功失败

>>> 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

但是当shell = True时,似乎无法确定Popen()调用是否成功。

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

赞赏的想法。

此致 马尔科姆

2 个答案:

答案 0 :(得分:15)

returncode会有效,但在您致电None之前它会p.poll()poll()本身将返回错误代码,因此您可以执行

if a.poll() != 0:
    print ":("

答案 1 :(得分:5)

在第一种情况下,它无法启动,在第二种情况下 - 它成功启动了shell,而shell又无法执行应用程序。因此,您的流程已正确生成,退出并等待您查询其退出代码。所以,问题是,除非你的shell或环境(例如没有内存)被彻底打破,否则Popen本身无法失败

因此,您可以放心.poll().wait()来获取所有可悲的新闻。