0

Is there a clear way to create a timeout function like the signal module but is compatible with Windows? Thanks

Daniel Engel
  • 158
  • 3
  • 13
  • 1
    Do you mean`time.sleep()`? – ᴀʀᴍᴀɴ Jan 27 '17 at 19:38
  • yes, using the time.sleep – Daniel Engel Jan 27 '17 at 19:39
  • 2
    What do you mean by "clear"? There has been a lot written about this problem around the net if you search for "windows python timeout". If you've searched around for this already, what did you find unclear about what's already out there? Is there a particular Python function that you need to timeout, or are you trying to write a function that can accept any other function and give it a timeout? – skrrgwasme Jan 27 '17 at 19:42
  • I agree with @skrrgwasme. But also, what is wrong with `signal`? It works on Windows with only a few exceptions. – RobertB Jan 27 '17 at 19:50
  • 4
    Possible duplicate of [right way to run some code with timeout in Python](http://stackoverflow.com/questions/6947065/right-way-to-run-some-code-with-timeout-in-python) – Aaron Jan 27 '17 at 20:00

1 Answers1

1

Yes, it can be done in windows without signal and it will also work in other os as well. 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):
    print("abc")
    #other stuff here

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