我有一个 python 脚本,它使用 subprocess 模块打开一个 .exe 程序。这个 .exe 程序是一个无限迭代的脚本,因为它将继续打印每次迭代的结果,直到用户关闭窗口。每隔一段时间,它将迭代结果打印到一个文件中,替换文件中以前的数据。
我的目标是:
- 运行 .exe 程序,并测试它输出的文件是否存在。
- 显示文件存在后,我需要对该文件运行测试以查看迭代是否已收敛到给定的公差范围内。迭代收敛后,我需要终止 .exe 子进程。
这是我当前的代码。它旨在在创建迭代文件后终止子进程:
import subprocess
from subprocess import Popen, PIPE
fileexists = False
iteratecomms = Popen('iterate.exe', stdout=PIPE, stdin=PIPE, stderr=PIPE)
# Begin the iteration. Need to select options 1 and then 1 again at program menu
out, err = iteratecomms.communicate("1\n1\n".encode())
while (fileexists == False):
fileexists = os.path.exists(filelocation)
else:
Popen.kill(iteratecomms)
我知道这是不正确的;问题是,一旦我开始 out, err = iteratecomms.communicate("1\n1\n".encode())
行,程序就开始迭代,并且不会继续下一组python代码。本质上,我需要启动.exe程序,同时测试文件是否已经创建。但是,我不能这样做,因为程序会无限期地运行。
我该如何解决这个问题?我假设继续执行第 2 步(在特定条件下测试文件并终止子进程)不会在此基础上做太多工作;如果这不是真的,我将如何完成我的所有目标?
非常感谢您的帮助!
编辑:阐明外部文件被覆盖。
最佳答案
我会使用多处理模块。
pool = multiprocessing.Pool()
def start_iteration():
return Popen('iterate.exe', stdout=PIPE, stdin=PIPE, stderr=PIPE)
pool.apply_async(start_iteration)
while (fileexists == False):
fileexists = os.path.exists(filelocation)
Popen.kill(???)
现在唯一的问题是您必须以某种方式找到进程的 PID,而无需等待 Popen 返回(因为 Popen 永远不会返回。)
关于Python:结束一个无限迭代的子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17661623/