Skip to main content
 首页 » 编程设计

Python之程序崩溃后继续程序

2025年02月15日9虾米哥

我有一个应用程序,当我给它一个特定的输入时它崩溃了。在命令行提示符下,我可以看到“访问冲突”消息等。 程序在处理输入时不会终止(一种永无止境的循环)。要杀死它,我需要键入 Ctrl+C。

My question is: How can I skip that crash programmatically ?

I mean: My goal is to give that input to that program, if it crashes I want to store the input and if it does not crash, then I will remove the input and continue with the next input?

我的代码是:

import subprocess 
 
 
program_to_call = "C:\\Program Files\\Software\\application.exe" 
arg = "-s" 
 
file = "C:\\Users\\test\\Desktop\\Project\\templates\\file1" 
 
subprocess.Popen([program_to_call, arg, file], shell=True)   # <---after this line, it does not go to next line  
 
... code for removing etc.  

由于我正在学习 Python,我希望在您的回答中看到一些有用的 Python 库的建议、概念或提示,以解决我的问题。您不需要编写代码片段。

注意:我使用的是 Windows 7(x86),安装的 python 版本是 2.7.1。

请您参考如下方法:

首先您需要弄清楚程序是将错误消息写入STDERR 还是STDOUT。那么您一定希望它在打印错误消息后刷新其缓冲区。最后,您可以这样做:

p = subprocess.Popen([program_to_call, ...], stdout=subprocess.PIPE)  # or stderr=... 
while True: 
    out, err = p.communicate() 
    # now check whether error message is in out (or err) 
    if p.returncode is not None: # process is dead 
        break 

如果您提供参数 stdout=subprocess.PIPE(与 stderr 类似),它将成功,因此您可以根据需要检查文本的输出。这可以通过读取文件对象 p.stdout 或使用 p.communicate() 来完成,它具有填充 p 的良好副作用.returncode 如果进程不再存在。

如果此解决方案不起作用,则您调用的程序可能不会刷新其输出流的缓冲区,对此您无能为力。