我正在使用Python使用subprocess模块调用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之后添加了一个额外的加薪,因此除了子进程之外,Python程序也被中断了。
编辑:根据eryksun的注释将pass更改为time.sleep(0.1),以减少CPU消耗。
关于python - 使用KeyboardInterrupt终止子进程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/39499959/