CTRL + C不会在Python中使用CTYPES中断对共享库的调用

Dus*_*rea 7 c python ctypes signals shared-libraries

当调用在C共享库(动态库)中执行的循环时,Python将不会收到KeyboardInterrupt,并且没有任何内容会响应(或处理)CTRL + C.

我该怎么办?

jfs*_*jfs 4

除非你使用PyDLLPYFUNCTYPE; GIL 在 ctypes 调用期间被释放。KeyboardInterrupt因此,如果 C 代码没有安装自己的信号处理程序,Python 解释器应该通过在主线程中引发来处理 SIGINT 。

让Python代码在主线程中运行;您可以将 ctypes 调用放入后台线程:

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)
Run Code Online (Sandbox Code Playgroud)