Python的过程中不会调用atexit
-
23-09-2019 - |
题
我想在atexit
使用Process
,但不幸的是它似乎并没有工作时。下面是一些示例代码:
import time
import atexit
import logging
import multiprocessing
logging.basicConfig(level=logging.DEBUG)
class W(multiprocessing.Process):
def run(self):
logging.debug("%s Started" % self.name)
@atexit.register
def log_terminate():
# ever called?
logging.debug("%s Terminated!" % self.name)
while True:
time.sleep(10)
@atexit.register
def log_exit():
logging.debug("Main process terminated")
logging.debug("Main process started")
a = W()
b = W()
a.start()
b.start()
time.sleep(1)
a.terminate()
b.terminate()
此代码的输出是:
DEBUG:root:Main process started DEBUG:root:W-1 Started DEBUG:root:W-2 Started DEBUG:root:Main process terminated
我希望,当W.run.log_terminate()
和a.terminate()
被称为b.terminate()
会被调用,并且输出被什么东西likeso(强调):
DEBUG:root:Main process started DEBUG:root:W-1 Started DEBUG:root:W-2 Started DEBUG:root:W-1 Terminated! DEBUG:root:W-2 Terminated! DEBUG:root:Main process terminated
为什么不是该工作,并且在那里记录的消息(从Process
上下文)当Process
终止更好的方法?
感谢您的输入 - 这是大加赞赏。
。解决方案
修改:基于由Alex马尔泰利建议的解决方案,如所预期以下工作:
import sys
import time
import atexit
import signal
import logging
import multiprocessing
logging.basicConfig(level=logging.DEBUG)
class W(multiprocessing.Process):
def run(self):
logging.debug("%s Started" % self.name)
def log_terminate(num, frame):
logging.debug("%s Terminated" % self.name)
sys.exit()
signal.signal(signal.SIGTERM, log_terminate)
while True:
time.sleep(10)
@atexit.register
def log_exit():
logging.debug("Main process terminated")
logging.debug("Main process started")
a = W()
b = W()
a.start()
b.start()
time.sleep(1)
a.terminate()
b.terminate()
这是值得的注意atexit
文档中的以下意见:
注意:当所述程序由信号,当检测到一个Python致命内部错误时,或者当os._exit()被调用杀死不叫从这个模块中注册的功能
不隶属于 StackOverflow