我写了这个简单的代码:
#!/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
答案 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