“Proper” way to handle signals other than SIGINT in Python?

雨燕双飞 提交于 2019-12-06 01:01:14

Or use a closure:

import os
import signal

def create_handler(obj):
    def _handler(signum, frame):
        print "obj is availiable here!"
        print obj
        signal.signal(signum, signal.SIG_DFL)
        os.kill(os.getpid(), signum) # Rethrow signal, this time without catching it
    return _handler

def mymethod(*params):
  obj = MyObj(params)
  signal.signal(signal.SIGTSTP, create_handler(obj))
  obj.do_some_long_stuff()   

create_handler(obj) returns a handler function with access to obj.

That would work under the condition that handler is a class-method and contains the self-member.

You could make obj global, since than you can access it from each function.

import os
import signal
obj = None

def handler(signum, frame):
    log_stop(obj)
    signal.signal(signum, signal.SIG_DFL)
    os.kill(os.getpid(), signum) # Rethrow signal, this time without catching it

def mymethod(*params):
    global obj # to signal that the obj we are changing here is the global obj

    obj = MyObj(params)
    handler.obj = obj
    signal.signal(signal.SIGTSTP, handler)
    obj.do_some_long_stuff()

(Note: Personally I avoid global parameters as much as possible, since global means really global).

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