Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/357.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 未能捕获特定错误_Python_Import - Fatal编程技术网

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

应该是
子进程。称为进程错误