3

All I want to do is timeout a function if it does not return before that

It all started because urllib2 supports timeout for urlopen, but not for reading part and my program hangs. Changing defaulttimeout for sockets does not work. Using signal.sigalrm does not work. I can't switch to requests because then I will have to rewrite and test a lot more.

I DON'T want to make a thread run the function and then timeout the thread, I want to timeout the function. Any ideas how?

Eric Cartman
  • 114
  • 10

2 Answers2

0

I like to use David's class here in my projects. I find it's very effective and I like that it provides a simple way to implement in existing code via a decorator. For example:

# Timeout after 30 seconds
@timeout(30)
def your_function():
    ...

CAUTION: This is not thread-safe! If you're using multithreading, the signal will get caught by a random thread. For single-threaded programs however, this is the easiest solution.

Community
  • 1
  • 1
Drewness
  • 5,004
  • 4
  • 32
  • 50
  • 4
    Unfortunately I am using windows, and signal.sigalrm is not supported by windows. The code you pointed at uses signal.sigalrm – Eric Cartman Mar 17 '14 at 13:17
0

Yes, it can be done in windows without signal and it will also work in other os as well. This is using thread but not to run the function but to raise a signal for timeout. The logic is to create a new thread and wait for a given time and raise an exception using _thread(in python3 and thread in python2). This exception will be thrown in the main thread and the with block will get exit if any exception occurs.

import threading
import _thread   # import thread in python2
class timeout():
  def __init__(self, time):
    self.time= time
    self.exit=False

  def __enter__(self):
    threading.Thread(target=self.callme).start()

  def callme(self):
    time.sleep(self.time)
    if self.exit==False:
       _thread.interrupt_main()  # use thread instead of _thread in python2
  def __exit__(self, a, b, c):
       self.exit=True

Usuage Example :-

with timeout(2):
    func()

The program in the with block should exit within 2 seconds otherise it will be exited after 2 seconds.

  • do not use this anywhere near your code, i dont think this is thread safe, the whole program will exit in my case – greendino Oct 26 '22 at 08:31