gpt4 book ai didi

python - 使用 KeyboardInterrupt 终止子进程

转载 作者:可可西里 更新时间:2023-11-01 09:47:25 25 4
gpt4 key购买 nike

我正在使用 Python 调用使用子进程模块的 C++ 程序。由于该程序需要一些时间才能运行,我希望能够使用 Ctrl+C 终止它。我在 StackOverflow 上看到了一些与此相关的问题,但似乎没有一个解决方案适合我。

我想要的是在 KeyboardInterrupt 上终止子进程。这是我的代码(类似于其他问题中的建议):

import subprocess

binary_path = '/path/to/binary'
args = 'arguments' # arbitrary

call_str = '{} {}'.format(binary_path, args)

proc = subprocess.Popen(call_str)

try:
proc.wait()
except KeyboardInterrupt:
proc.terminate()

但是,如果我运行它,代码将挂起等待进程结束并且永远不会注册 KeyboardInterrupt。我也尝试了以下方法:

import subprocess
import time

binary_path = '/path/to/binary'
args = 'arguments' # arbitrary

call_str = '{} {}'.format(binary_path, args)

proc = subprocess.Popen(call_str)
time.sleep(5)
proc.terminate()

此代码片段在终止程序时运行良好,因此问题不在于为终止而发送的实际信号。

如何更改代码以便子进程可以在 KeyboardInterrupt 上终止?

我正在运行 Python 2.7 和 Windows 7 64 位。提前致谢!

我试过的一些相关问题:

Python sub process Ctrl+C

Kill subprocess.call after KeyboardInterrupt

kill subprocess when python process is killed?

最佳答案

我想出了一种方法来做到这一点,类似于 Jean-Francois 对循环的回答,但没有多线程。关键是使用 Popen.poll() 来确定子进程是否已完成(如果仍在运行,将返回 None )。

import subprocess
import time

binary_path = '/path/to/binary'
args = 'arguments' # arbitrary

call_str = '{} {}'.format(binary_path, args)

proc = subprocess.Popen(call_str)

try:
while proc.poll() is None:
time.sleep(0.1)

except KeyboardInterrupt:
proc.terminate()
raise

我在 KeyboardInterrupt 之后添加了一个额外的 raise,因此除了子进程之外,Python 程序也被中断。

编辑:根据 eryksun 的评论将传递更改为 time.sleep(0.1) 以减少 CPU 消耗。

关于python - 使用 KeyboardInterrupt 终止子进程,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39499959/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com