有没有一种方法可以Ctrl+C基于Cython扩展中嵌入的循环来中断()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的东西。
慕虎7371278
婷婷同学_
相关分类