如何在不杀死解释器的情况下中断本机扩展代码? [英] How to interrupt native extension code without killing the interpreter?

查看:151
本文介绍了如何在不杀死解释器的情况下中断本机扩展代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个项目,它结合了用C ++编写的高性能算法和Python接口。 C ++类和函数通过Cython编译器封装并暴露给Python。

I am working on a project which combines high-performance algorithms written in C++ with a Python interface. C++ classes and functions are wrapped and exposed to Python via the Cython compiler.

假设我从Python解释器调用一个长期运行的本机函数(我首选的是IPython)。是否有可能在不杀死解释器的情况下中断或中止该代码的执行?

Suppose I call a long running native function from the Python interpreter (my preferred one is IPython). Is it somehow possible to interrupt or abort the execution of that code without killing the interpreter?

推荐答案

这是使用Ricardo C建议的多处理的可能实现。,

Here is a possible implementation using multiprocessing as suggested by Ricardo C.,

import multiprocessing as mpr
def dangerwrap(f):
  """
  I assume f is, or eventually calls, 
  some external function, like cython wrapped C/C++.
  Also assuming that f returns an
  object and takes no parameters
  """
  event  = mpr.Event()
  q = mpr.Queue()

  def signalling_f():
    q.put(f())
    event.set()

  f_process = mpr.Process(target = signalling_f)
  f_process.start()
  try:
    event.wait()

  except KeyboardInterrupt:
    f_process.terminate()
    f_process.join()
    print "Caught in dangerwrap"
    return None


  print "Exiting normally"
  return q.get()

现在代替,

X = f()

不会响应键盘中断,调用

which will not respond to keyboard interrupts, calling

X = dangerwrap(f)

将通过键盘中断正常停止。

will stop gracefully with a keyboard interrupt.

这篇关于如何在不杀死解释器的情况下中断本机扩展代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆