当shell = True时如何确定subprocess.Popen()失败 [英] How to determine subprocess.Popen() failed when shell=True

查看:502
本文介绍了当shell = True时如何确定subprocess.Popen()失败的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Windows版本的Python 2.6.4:使用shell = True时,是否有任何方法可以确定subprocess.Popen()是否失败?

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

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

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

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

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

想法受到赞赏.

关于, 马尔科姆

推荐答案

returncode将起作用,尽管在您调用p.poll()之前它将是None. poll() 本身将返回错误代码,因此您可以执行以下操作

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 ":("

这篇关于当shell = True时如何确定subprocess.Popen()失败的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆