我正在使用python运行外部程序,如下所示
call("/usr/sbin/snif")
我得到
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/subprocess.py", line 480, in call
return Popen(*popenargs, **kwargs).wait()
File "/usr/lib/python2.6/subprocess.py", line 633, in __init__
errread, errwrite)
File "/usr/lib/python2.6/subprocess.py", line 1139, in _execute_child
raise child_exception
OSError: [Errno 2] No such file or directory
我如何获得最后一行,上面写着:
"没有这样的文件或目录"
或者更好的是,我怎么知道执行是否成功?
谢谢
您可以捕获错误:
try:
call('/usr/sbin/snif')
except OSError:
print "It didn't execute"
如果要查看命令是否正确执行,请改用 check_output
或 check_call
并捕获另一个错误:
import subprocess:
try:
subprocess.check_output('/usr/sbin/snif')
except OSError:
print 'That file does not exist'
except subprocess.CalledProcessError:
print 'Bad exit code'