Daniel Engel
Daniel Engel

Reputation: 158

Timeout Function in Python (For Windows)

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

Upvotes: 0

Views: 2347

Answers (1)

Sunil Kumar
Sunil Kumar

Reputation: 39

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.

Upvotes: 1

Related Questions