有没有办法根据嵌入在Cython扩展中的循环中断(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 '
! Received keyboard interrupt, quitting threads.
'
这将运行一个循环,它是C Cython扩展的一部分.
然后,在按下Ctrl C的同时,抛出KeyboardInterrupt但忽略,程序一直持续到模拟结束.
我找到的工作是通过捕获SIGINT信号来处理扩展内的异常:
#include
#include
static void handler(int sig)
{
// Catch exceptions
switch(sig)
{
case SIGABRT:
fputs("Caught SIGABRT: usually caused by an abort() or assert()
", stderr);
break;
case SIGFPE:
fputs("Caught SIGFPE: arithmetic exception, such as divide by zero
",
stderr);
break;
case SIGILL:
fputs("Caught SIGILL: illegal instruction
", stderr);
break;
case SIGINT:
fputs("Caught SIGINT: interactive attention signal, probably a ctrl+c
",
stderr);
break;
case SIGSEGV:
fputs("Caught SIGSEGV: segfault
", stderr);
break;
case SIGTERM:
default:
fputs("Caught SIGTERM: a termination request was sent to the program
",
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.