【发布时间】:2013-05-27 09:12:53
【问题描述】:
有没有办法根据嵌入在 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 '\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 的东西。
【问题讨论】:
标签: python cython keyboardinterrupt