获取使用子进程python的命令行执行引发的错误

问题描述 投票:1回答:1

我正在尝试检索python脚本本身中任何命令行执行所引发的错误(重要的是退出代码)。我为此使用子过程。当我执行任何错误的命令时,它将像往常一样在终端中引发错误,但是随后它停止执行python文件,并且我无法获得存储错误。

查看代码。 p_status应该存储退出代码。但是在打印之前,它将在终端中引发错误后停止脚本。

process = subprocess.Popen([<command>], stdout = subprocess.PIPE)
output = process.communicate()
p_status = process.wait()
print(p_status)

我经历了不同的解决方案,并尝试了所有解决方案,但未能获得所需的结果。

python command-line subprocess exit-code
1个回答
0
投票

使用以下代码解决了此问题:

try:
    subprocess.Popen([<command>], stdout = subprocess.PIPE)
except OSError as error:
    print(error.errno) #for exit code
© www.soinside.com 2019 - 2024. All rights reserved.