Python错误处理不能排除错误

2024-10-02 20:40:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在尝试以下代码:

try:
    res = subprocess.Popen('bgpq3 -4 {} -m 24 -l {}'.format('MAIyNT- 
AS38082','12414'), shell=True,
    universal_newlines=True,
    stdout=subprocess.PIPE).communicate()[0]
except Exception:
       print("Wrong")
       #do this code 

输出是?在

^{pr2}$

所以我不能使用错误处理!!在

有什么想法吗?在


Tags: 代码trueformatstdoutresshelluniversalsubprocess
2条回答

当你写except Exception:时,你没有捕捉到所有的异常:系统退出错误和操作系统错误(如BaseExceptionSystemExitKeyboardInterrupt和{})are excluded。在

大多数子进程的异常是^{}
由于您没有报告错误的完整回溯,所以我只能假设您得到了这些错误中的一个,您可以使用以下方法捕获它们:

except subprocess.CalledProcessError:

或者

^{pr2}$

正如PEP 8所建议的那样,您不应该单独使用except:,即使它在您的案例中可以工作。
作为一个经验法则,总是抓住你特别提出的精确异常!在

这里只处理exception类型的错误。您只需要使用except:。这样就可以捕获代码中发生的所有错误。在

try:
    #your code
except Exception as e:
    #handle the exception

有关更多信息,请参阅the docs我从一个快速谷歌得到的;)

相关问题 更多 >