Question

I want to stop executing R function called from python (rpy2) after 2 seconds. Here is python code:

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

It doesn't work. I must wait 10 seconds for signal handler.

Was it helpful?

Solution

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.

OTHER TIPS

Try setting your alarm and then putting the operation you want the timeout on inside of try catch blocks. The alarm should throw a catchable exception. Hope that makes sense, it works for me anyway.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top