python - 可执行文件失败时从subprocess.Popen()捕获错误

标签 python error-handling subprocess

任何人都可以建议对以下脚本进行一些改进,以便如果Application.exe文件失败,该脚本将结束而不是无限期地挂起?

application = r'.\Application.exe'
input_params = '-i Input_1 -j Input_2

process = (application,input_params)
p = subprocess.Popen(" ".join(process),shell= True, stderr=subprocess.STDOUT, stdout = subprocess.PIPE)
p.communicate()

当应用程序文件失败时,没有引发异常,是否有可能在这种情况下让子进程抛出一个异常?

编辑:实现了p.returncode语句。

若要修改我的原始问题,当Application.exe程序失败时,它将显示以下窗口

enter image description here

只有在我关闭此窗口后,程序才能继续执行(例如:p.returncode将返回值255)。

有没有办法不显示该窗口或自动关闭该窗口,或者尽管显示了该窗口也使程序继续运行?

问候

最佳答案

How to catch exception output from Python subprocess.check_output()?

try:
    subprocess.check_output(...)
except subprocess.CalledProcessError as e:
    print e.output
from subprocess import Popen, PIPE

p = Popen(['bitcoin', 'sendtoaddress', ..], stdout=PIPE, stderr=PIPE)
output, error = p.communicate()
if p.returncode != 0: 
   print("bitcoin failed %d %s %s" % (p.returncode, output, error))

关于python - 可执行文件失败时从subprocess.Popen()捕获错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55243993/

相关文章:

python - 使用 Python 列出 FTP 中所有子目录中的所有文件

c# - 数据流管道中的全局每 block 错误处理

Python - 子进程被终止后,多处理队列未按正确顺序返回结果

python - tensorflow 。如何张量板

python - 理解 Python 类和对象

python - tensorflow 对象检测训练模型不起作用

php - Laravel 处理异常

c# - 更完整的错误日志

python - 如何使用Python子进程添加到VLC播放列表队列

python - subprocess.check_output 更快的方法