使用KeyboardInterrupt终止子进程 [英] Terminating a subprocess with KeyboardInterrupt

查看:434
本文介绍了使用KeyboardInterrupt终止子进程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm using Python to call a C++ program using the subprocess module. Since the program takes some time to run, I'd like to be able to terminate it using Ctrl+C. I've seen a few questions regarding this on StackOverflow but none of the solutions seem to work for me.

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

What I would like is for the subprocess to be terminated on KeyboardInterrupt. This is the code that I have (similar to suggestions in other questions):

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.我也尝试了以下方法:

However, if I run this, the code is hung up waiting for the process to end and never registers the KeyboardInterrupt. I have tried the following as well:

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()

此代码段可在终止程序时正常工作,因此问题并非发送给终止的实际信号.

This code snippet works fine at terminating the program, so it's not the actual signal that's being sent to terminate that is the problem.

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

How can I change the code so that the subprocess can be terminated on KeyboardInterrupt?

我正在运行Python 2.7和Windows 7 64位.预先感谢!

I'm running Python 2.7 and Windows 7 64-bit. Thanks in advance!

我尝试过的一些相关问题:

Some related questions that I tried:

Python子进程Ctrl + C

在KeyboardInterrupt之后杀死子进程.

杀死python进程时杀死kill子进程?

推荐答案

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

I figured out a way to do this, similar to Jean-Francois's answer with the loop but without the multiple threads. The key is to use Popen.poll() to determine if the subprocess has finished (will return None if still running).

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之后增加了一个额外的加薪,因此除了子进程之外,Python程序也被中断了.

I added an additional raise after KeyboardInterrupt so the Python program is also interrupted in addition to the subprocess.

根据eryksun的注释将传递更改为time.sleep(0.1),以减少CPU消耗.

Changed pass to time.sleep(0.1) as per eryksun's comment to reduce CPU consumption.

这篇关于使用KeyboardInterrupt终止子进程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆