Stopping a third party function

独自空忆成欢 提交于 2019-12-20 05:15:38

问题


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 signal (can be using Signal or any other flag I watch) to terminate I want to terminate the callable's execution on the spot (without exiting the process of course)

class FooRunner(object):
    def goo(self, foo):
        try:
            foo()
         except:
            pass

     def on_stop_signal(self):
            pass

回答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




回答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/python
import time
import signal
import threading


class MyException(Exception):
    pass


class FooRunner(object):
    def goo(self, foo):
        try:
            signal.signal(signal.SIGALRM, self.on_stop_signal)
            foo()
        except MyException:
            print('caugt alarm exception')

    def on_stop_signal(self, *args):
        print('alarm triggered')
        raise MyException()


def sample_foo():
    time.sleep(30)


def stop_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



来源:https://stackoverflow.com/questions/34834729/stopping-a-third-party-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!