Mal*_*olm 7 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
Run Code Online (Sandbox Code Playgroud)
但是当shell = True时,似乎无法确定Popen()调用是否成功.
>>> p = subprocess.Popen( 'Nonsense.application', shell=True )
>>> p
>>> subprocess.Popen object at 0x0275FF90>>>
>>> p.pid
6620
>>> p.returncode
>>>
Run Code Online (Sandbox Code Playgroud)
想法赞赏.
此致,马尔科姆
Mic*_*zek 15
returncode会工作,虽然None直到你打电话p.poll().poll()本身将返回错误代码,所以你可以这样做
if a.poll() != 0:
print ":("
Run Code Online (Sandbox Code Playgroud)
在第一种情况下,它无法启动,在第二种情况下 - 它成功启动了shell,而shell又无法执行应用程序.因此,您的流程已正确生成,退出并等待您查询其退出代码.所以,问题是,除非你的shell或环境(例如没有内存)被彻底打破,否则Popen它本身就不会失败.
所以,你可以放心地.poll()和.wait()它让所有的噩耗.