Ctrl+C
)Python脚本?我有以下Python脚本:
def main():
# Intantiate simulator
sim = PySimulator()
sim.Run()
if __name__ == "__main__":
# Try to deal with Ctrl+C to abort the running simulation in terminal
# (Doesn't work...)
try:
sys.exit(main())
except (KeyboardInterrupt, SystemExit):
print '\n! Received keyboard interrupt, quitting threads.\n'
这段代码是C++ Cython扩展中的循环。
当按下Ctrl+C
时,就会抛出KeyboardInterrupt
异常,但程序会忽略它并继续运行,直到模拟结束。
我找到的解决方法是,在扩展中捕获SIGINT
信号以处理异常:
#include <execinfo.h>
#include <signal.h>
static void handler(int sig)
{
// Catch exceptions
switch(sig)
{
case SIGABRT:
fputs("Caught SIGABRT: usually caused by an abort() or assert()\n", stderr);
break;
case SIGFPE:
fputs("Caught SIGFPE: arithmetic exception, such as divide by zero\n",
stderr);
break;
case SIGILL:
fputs("Caught SIGILL: illegal instruction\n", stderr);
break;
case SIGINT:
fputs("Caught SIGINT: interactive attention signal, probably a ctrl+c\n",
stderr);
break;
case SIGSEGV:
fputs("Caught SIGSEGV: segfault\n", stderr);
break;
case SIGTERM:
default:
fputs("Caught SIGTERM: a termination request was sent to the program\n",
stderr);
break;
}
exit(sig);
}
然后:
signal(SIGABRT, handler);
signal(SIGFPE, handler);
signal(SIGILL, handler);
signal(SIGINT, handler);
signal(SIGSEGV, handler);
signal(SIGTERM, handler);
我能不能从Python或者Cython中实现这个功能呢?因为我将要在Windows/MinGW下移植我的扩展,所以我希望有一些不那么依赖于Linux的东西。
PyErr_CheckSignals()
在 Windows 上能否处理 Ctrl-C 信号?我选择在主线程中使用while sim.running: time.sleep(1)
循环来避免隐式信号检查,只要另一个线程中的 Cython 代码定期释放 GIL 就可以工作。+1 for the explanation. - jfs