使用python subprocess.run进行异常处理

我是Python的新手。我需要从subprocess.run捕获所有错误/异常。

当前,我有一个包含subprocess.run( shell script )[运行shell脚本]

的Python文件。

我需要捕获此过程中的所有异常,

我尝试了除'异常,例如e:print(e)',但看不到所有错误。

hewei600 回答:使用python subprocess.run进行异常处理

根据文档subprocess.check_output()_doc,您可以按以下方式处理异常:

try:
    subprocess.run(...)
except subprocess.CalledProcessError as e:
    print e.output
,

像这样使用 check_returncode():

#!/usr/bin/env python3

import subprocess

try:
    ls = subprocess.run( ("ls","-w"),stdout=subprocess.PIPE,stderr=subprocess.PIPE )
    ls.check_returncode()
except subprocess.CalledProcessError as e:
    print ( "Error:\nreturn code: ",e.returncode,"\nOutput: ",e.stderr.decode("utf-8") )
    raise

print ( ls.stdout.decode("utf-8") )

这会运行“ls -w”,它返回一个错误(-w 需要一个参数),触发异常处理,打印返回代码和 stderr 输出,并重新引发异常。如果您尝试使用“ls -l”来代替,它将成功运行该命令并打印其输出。

本文链接:https://www.f2er.com/3104987.html

大家都在问