Stopping A Third Party Function
This is part of a complex project, I will try and simplify it. I have a class that gets a callable and executes it, the callable can run for any duration of time. If I get a signa
Solution 1:
On a single-threaded signal not running on Windows, (i.e., any Unix flavor) you can use signal.alarm for that.
Check the first example on the documentation - it is more or less what you are asking for: https://docs.python.org/2/library/signal.html
Solution 2:
If anyone ever needs this here is a code sample of it working (One thing to note signal.signal
can be called only from the main thread):
#!/usr/bin/pythonimport time
import signal
import threading
classMyException(Exception):
passclassFooRunner(object):
defgoo(self, foo):
try:
signal.signal(signal.SIGALRM, self.on_stop_signal)
foo()
except MyException:
print('caugt alarm exception')
defon_stop_signal(self, *args):
print('alarm triggered')
raise MyException()
defsample_foo():
time.sleep(30)
defstop_it():
signal.alarm(3)
print('alarm was set for 3 seconds')
if __name__ == "__main__":
print('starting')
fr = FooRunner()
t = threading.Thread(target=stop_it)
t.start()
fr.goo(sample_foo)
Thanks @jsbueno
Post a Comment for "Stopping A Third Party Function"