8

Windows 版本的 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
>>>

想法赞赏。

问候,马尔科姆

4

2 回答 2

16

returncode会起作用,尽管它会在None你调用p.poll(). poll()本身会返回错误代码,所以你可以这样做

if a.poll() != 0:
    print ":("
于 2010-05-18T22:27:32.580 回答
5

在第一种情况下,它无法启动,在第二种情况下 - 它成功启动了 shell,而 shell 又无法执行应用程序。因此,您的进程已正确生成、退出并等待您查询其退出代码。因此,问题是,除非您的外壳或环境(例如,没有内存)完全损坏,否则Popen它本身不可能失败

所以,你可以安全地.poll().wait()它上面得到所有的坏消息。

于 2010-05-18T22:27:22.833 回答