Python:结束一个无限迭代的子进程

标签 python subprocess popen

我有一个 python 脚本,它使用 subprocess 模块打开一个 .exe 程序。这个 .exe 程序是一个无限迭代的脚本,因为它将继续打印每次迭代的结果,直到用户关闭窗口。每隔一段时间,它将迭代结果打印到一个文件中,替换文件中以前的数据。

我的目标是:

  1. 运行 .exe 程序,并测试它输出的文件是否存在。
  2. 显示文件存在后,我需要对该文件运行测试以查看迭代是否已收敛到给定的公差范围内。迭代收敛后,我需要终止 .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/

相关文章:

python - subprocess.run 在 Windows 中不起作用 - 系统找不到指定的文件

python - 从 0 到 n 的数字中数字出现的次数

python - 如何在matplotlib中标记补丁

python - 如何展平解析树并存储在字符串中以进行进一步的字符串操作python nltk

python - 斐波那契加法器 - 计算斐波那契数列中的数字

python - 在 Windows 上,如何使用 Python 2.7 子进程保护 shell 脚本的参数?

python - 完全独立于脚本运行命令

c++ - popen 管道执行程序并读取输出的替代方案

php - popen 失败,返回 "sh: <command>: not found"

c++ - 跨 unix 文件系统使用带有 popen 的 FILE 描述符时崩溃