[英]How to know what the error is when I use subprocess.run() in python with exception?
我正在将bash代码转换为python。
我通过python中的subprocess.run()使用bash的mkdir。
在以下示例中,subprocess.run()引发异常。
但是我无法检查错误是什么,因为我无法获得subprocess.run()返回的结果对象。
有什么聪明的方法可以知道错误是什么吗? 还是我不应该在这里使用“尝试例外”?
import sys
import subprocess
directory = '/tmp/test_dir'
options = ''
try:
result=subprocess.run(['mkdir', options, directory], check=True)
except subprocess.CalledProcessError as ex:
print("In this example, subprocess.run() above raise an exception CalledProcessError.")
# print("I would like to check result.returncode = {0}. But it failed because object 'result' is not defined.".format(result.returncode))
except Exception as ex:
sys.stderr.write("This must not happen.")
sys.exit(1)
非常感谢你。
你总是可以做
import subprocess
# make the subprocess
pr = subprocess.Popen(['your', 'command', 'here'], stdout=subprocess.PIPE, stderr=subprocess.PIPE)
# blocks until process finishes
out, err = pr.communicate()
# check the return code
if pr.returncode != 0:
sys.stderr.write("oh no")
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.