Python 未能捕获特定错误
我编写了以下简单代码:Python 未能捕获特定错误,python,import,Python,Import,我编写了以下简单代码: #!/usr/bin/python2.7 -tt import subprocess def main() try: process = subprocess.check_output(['unvalidcommand'],shell=True) except CalledProcessError: print 'there is the calledProcessError' if __name__ == '__main__': ma
#!/usr/bin/python2.7 -tt
import subprocess
def main()
try:
process = subprocess.check_output(['unvalidcommand'],shell=True)
except CalledProcessError:
print 'there is the calledProcessError'
if __name__ == '__main__':
main()
预期输出:存在被调用的进程错误
我得到的信息:name错误:未定义全局名称“CalledProcessError”
def main():
try:
process = subprocess.check_output(['unvalidcommand'],shell=True)
except subprocess.CalledProcessError: # need to use subprocess.CalledProcessError
print 'there is the calledProcessError'
main()
there is the calledProcessError
/bin/sh: 1: unvalidcommand: not found
或者只需从子流程导入所需:
from subprocess import check_output,CalledProcessError
def main():
try:
process = check_output(['unvalidcommand'],shell=True)
except CalledProcessError:
print 'there is the calledProcessError'
main()
不是一个内置的例外。您需要限定异常名称才能使用它
except subprocess.CalledProcessError:
^^^^^^^^^^^
或者您需要显式导入它:
from subprocess import CalledProcessError
应该是子进程。称为进程错误
。