1

我想在 2 秒后停止执行从 python (rpy2) 调用的 R 函数。这是python代码:

signal.signal(signal.SIGALRM, handler)
signal.alarm(2) # set timeout to 2 seconds

# run R code
result = robjects.r('''
      Sys.sleep(10) 
      return("hello")
   ''')

signal.alarm(0) # disable alarm

它不起作用。我必须等待 10 秒等待信号处理程序

4

2 回答 2

1

The evaluation of R code does not release the Python GIL. The only way to get a Python script to monitor the execution time of R code is to have two processes.

You could check the unit test for rpy2 "testInterruptR()", although there are much more elegant ways to implement that in an application. There a SIGINT is sent to an R process running an infinite loop.

于 2012-03-06T07:03:18.363 回答
1

尝试设置您的警报,然后将您希望超时的操作放在 try catch 块内。警报应该抛出一个可捕获的异常。希望这是有道理的,无论如何它对我有用。

于 2012-05-20T21:40:45.830 回答