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