0

我正在使用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

我如何得到最后一行,上面写着:

“没有相应的文件和目录”

或者更好的是,我怎么知道执行是否成功?

谢谢

4

1 回答 1

1

你可以捕捉到错误:

try:
    call('/usr/sbin/snif')
except OSError:
    print "It didn't execute"

如果您想查看命令是否正确执行,请使用check_outputorcheck_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'
于 2012-12-09T10:16:52.710 回答