python - 使用 KeyboardInterrupt 终止子进程

标签 python windows subprocess interrupt terminate

我正在使用 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/

相关文章:

python - Julia 符号和数字性能对比 Python

windows - 检测尚未与无线网络建立任何连接的无线计算机

windows - 使用 shell 命令在 vba 中执行批处理文件不起作用

python - Python 中 CSV 列的列表

python - 返回图像的函数的类型提示是什么?

python - 如何使用子进程强制 python 释放内存?

java - 从 Java 开始忽略/捕获子进程输出的最简单方法

python - 如何将 rfcomm shell 命令的结果放入 python 中的变量中?

python - django - 不显示模板文件中的更改

windows - 调用已释放的 COM 对象