简体   繁体   English

Boost.Python 和 Python 异常

[英]Boost.Python and Python exceptions

How can I make boost.python code python exceptions aware?如何使 boost.python 代码 python 异常感知?

For example,例如,

int test_for(){
  for(;;){
  }
  return 0;
}

doesn't interrupt on Ctrl-C, if I export it to python. I think other exceptions won't work this way to.如果我将它导出到 python,则不会在 Ctrl-C 上中断。我认为其他异常不会以这种方式工作。

This is a toy example.这是一个玩具示例。 My real problem is that I have a C function that may take hours to compute.我真正的问题是我有一个 C function 可能需要几个小时来计算。 And I want to interrupt it, if it takes more that hour for example.我想打断它,例如,如果它需要更多的时间。 But I don't want to kill python instance, within the function was called.但我不想杀死python实例,在function内被调用。

Thanks in advance.提前致谢。

In your C or C++ code, install a signal handler for SIGINT that sets a global flag and have your long-running function check that flag periodically and return early when the flag is set.在您的 C 或 C++ 代码中,为 SIGINT 安装一个设置全局标志的信号处理程序,并让您长期运行的 function 定期检查该标志并在设置标志时提前返回。 Alternatively, instead of an early return, you can raise a Python exception using the Python C API: see PyErr_SetInterrupt here .或者,您可以使用 Python Python C API 引发 Python 异常,而不是提前返回:请参阅此处的 PyErr_SetInterrupt。

I am not sure boost.python has a solution - you may have to deal with this by yourself.我不确定 boost.python 是否有解决方案 - 您可能需要自己处理。 In which case it is no different than conventional signal handling.在这种情况下,它与传统的信号处理没有什么不同。 The easy solution is to have a global variable which is changed by the signal handler, and to check this variable regularly .简单的解决方案是拥有一个由信号处理程序更改的全局变量,并定期检查该变量 The other solution is to use setjmp/longjmp, but I think the first way is best when applicable, because it is simple and much more maintainable.另一种解决方案是使用 setjmp/longjmp,但我认为第一种方法在适用时最好,因为它简单且更易于维护。

Note that this is unix specific - I don't know how this works on windows.请注意,这是特定于 unix 的——我不知道它在 windows 上是如何工作的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM