在Python中调用call()时出错

2024-04-24 08:06:04 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我怎么才能得到最后一行,上面写着:

“没有这样的文件或目录”

或者更好的是,我如何知道执行是否成功?你知道吗

谢谢


Tags: inpy程序childmostlibusrline
1条回答
网友
1楼 · 发布于 2024-04-24 08:06:04

您可以捕获错误:

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

如果要查看命令是否正确执行,请改用check_outputcheck_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'

相关问题 更多 >