Python异步方法中SIGTERM信号处理异常问题求助
问题:SIGTERM信号无法触发异步清理逻辑,SIGINT正常工作
我尝试捕获SIGINT和SIGTERM信号以实现程序优雅退出。目前SIGINT能正常工作:程序进入信号处理函数,完成任务清理后退出;但触发SIGTERM时程序直接退出,不会执行清理逻辑。由于参考的原代码多数无法在Python 3.12运行,我将两个示例混合写成了如下代码:
import asyncio import functools import signal async def signal_handler(sig, loop): """ Exit cleanly on SIGTERM ("docker stop"), SIGINT (^C when interactive) """ print('caught {0}'.format(sig.name)) tasks = [task for task in asyncio.all_tasks() if task is not asyncio.current_task()] list(map(lambda task: task.cancel(), tasks)) results = await asyncio.gather(*tasks, return_exceptions=True) print('finished awaiting cancelled tasks, results: {0}'.format(results)) loop.stop() if __name__ == "__main__": loop = asyncio.new_event_loop() asyncio.ensure_future(task1(), loop=loop) asyncio.ensure_future(task2(), loop=loop) loop.add_signal_handler(signal.SIGTERM, functools.partial(asyncio.ensure_future, signal_handler(signal.SIGTERM, loop))) loop.add_signal_handler(signal.SIGINT, functools.partial(asyncio.ensure_future, signal_handler(signal.SIGINT, loop))) try: loop.run_forever() finally: loop.close()
其中task1可立即终止,但task2的清理代码在SIGINT触发后会执行,SIGTERM触发后却不执行。
内容的提问来源于stack exchange,提问作者Auspex
相关产品推荐
相关产品推荐

