CTRL + C不会在Python中使用CTYPES中断对共享库的调用 [英] CTRL+C doesn't interrupt call to shared-library using CTYPES in Python
问题描述
当调用在C共享库(动态库)中执行的循环时,Python将不会收到KeyboardInterrupt,并且没有任何响应(或处理)CTRL + C。
When calling a loop being performed in a C shared-library (dynamic library), Python will not receive a KeyboardInterrupt, and nothing will respond (or handle) CTRL+C.
我该怎么办?
推荐答案
除非您使用 PyDLL
或 PYFUNCTYPE
; GIL在ctypes调用期间被释放。因此,如果C代码未安装自己的信号处理程序,Python解释器应通过在主线程中引发 KeyboardInterrupt
来处理SIGINT。
Unless you use PyDLL
or PYFUNCTYPE
; the GIL is released during the ctypes calls. Therefore the Python interpreter should handle SIGINT by raising KeyboardInterrupt
in the main thread if the C code doesn't install its own signal handler.
允许Python代码在主线程中运行;您可以将ctypes调用放入后台线程中:
To allow the Python code to run in the main thread; you could put the ctypes call into a background thread:
import threading
t = threading.Thread(target=ctypes_call, args=[arg1, arg2, ...])
t.daemon = True
t.start()
while t.is_alive(): # wait for the thread to exit
t.join(.1)
这篇关于CTRL + C不会在Python中使用CTYPES中断对共享库的调用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!