0

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

5
  • 1
    Do you meantime.sleep()? Commented Jan 27, 2017 at 19:38
  • yes, using the time.sleep Commented Jan 27, 2017 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? Commented Jan 27, 2017 at 19:42
  • I agree with @skrrgwasme. But also, what is wrong with signal? It works on Windows with only a few exceptions. Commented Jan 27, 2017 at 19:50
  • 4
    Possible duplicate of right way to run some code with timeout in Python Commented Jan 27, 2017 at 20:00

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.