未能捕获到特定错误

时间:2014-07-31 12:27:02

标签: 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__':
  main() 

预期输出:there is the calledProcessError

我得到了什么:NameError: global name 'CalledProcessError' is not defined

2 个答案:

答案 0 :(得分:12)

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

或者只是从subprocess

导入您需要的内容
from subprocess import check_output,CalledProcessError

def main():
  try:
    process = check_output(['unvalidcommand'],shell=True)
  except CalledProcessError:
    print 'there is the calledProcessError'
main()

答案 1 :(得分:4)

subprocess.CalledProcessError不是内置异常。您需要限定异常名称才能使用它。

except subprocess.CalledProcessError:
       ^^^^^^^^^^^

或者您需要明确导入它:

from subprocess import CalledProcessError