4

我有一个函数负责在程序结束时杀死一个子进程:

class MySingleton:
    def __init__(self):
        import atexit
        atexit.register(self.stop)

    def stop(self):
        os.kill(self.sel_server_pid, signal.SIGTERM)

但是,当调用此函数时,我收到一条错误消息:

Traceback (most recent call last):
File "/usr/lib/python2.5/atexit.py", line 24, in _run_exitfuncs
   func(*targs, **kargs)
File "/home/commando/Development/Diploma/streaminatr/stream/selenium_tests.py", line 66, in stop
   os.kill(self.sel_server_pid, signal.SIGTERM)
AttributeError: 'NoneType' object has no attribute 'kill'

看起来osandsignal模块在被调用之前被卸载atexit。重新导入它们可以解决问题,但这种行为对我来说似乎很奇怪 - 这些模块是在我注册我的处理程序之前导入的,那么为什么在我自己的退出处理程序运行之前将它们卸载?

4

1 回答 1

9

对于程序终止时销毁的顺序没有强有力的保证,因此最好确保atexit-registered 函数是自包含的。例如,在您的情况下:

class MySingleton:
    def __init__(self):
        import atexit
        atexit.register(self.stop)
        self._dokill = os.kill
        self._thesig = signal.SIGTERM

    def stop(self):
        self._dokill(self.sel_server_pid, self._thesig)

This is preferable to re-importing modules (which could conceivably cause slowdown of program termination and even unending loops, though that risk is lesser for "system-supplied" modules such as os).

于 2010-04-03T18:15:34.593 回答