首页 > 解决方案 > 打开可执行文件,然后不久将其关闭

问题描述

因此,我正在编写的 python 代码的目的是更改应用程序的配置文件,运行该应用程序,然后在 20 秒后关闭它,直到我停止代码。它看起来像这样:

while True:

    with open(filePath,"w") as f:
        f.write(text)
        f.close()

    subprocess.check_call([executablePath])
    
    time.sleep(20)

但是,subprocess.check_call()我找到的函数 不让代码继续。此外,我找不到关闭正在运行的可执行文件的功能。

所以,总而言之,我需要一个打开可执行文件然后让代码继续运行的函数,然后是一个关闭正在运行的可执行文件(同一个)的函数。

抱歉,如果我遗漏了一些明显的东西。

标签: pythonexe

解决方案


您可以在run子进程时设置超时:

with open(filePath,"w") as f:
    f.write(text)
    f.close()

try:
    subprocess.run([executablePath], check=True, timeout=20)
except TimeoutExpired:
    pass

您也可以传递timeoutcheck_call

with open(filePath,"w") as f:
    f.write(text)
    f.close()

try:
    subprocess.check_call([executablePath], timeout=20)
except TimeoutExpired:
    pass

推荐阅读