我的程序在主线程中运行之后,我发送一个signal.SIGINT信号来中断程序并导致退出。程序关闭,但是由于某种原因未调用信号处理程序,我需要调用信号处理程序来运行一些清理代码。
我目前正在运行:
-Windows 10
-Python 3.7.3 x64
我尝试从内置信号模块发送多个不同的信号,例如SIGINT,SIGTERM和CTRL_C_EVENT。在所有情况下,程序流都将中断并退出程序,但是不会调用signal_handler。
我知道所有信号都只能由main函数接收,所以我试图在代码中坚持这一点。
位置:
client =来自重写的不合格客户端对象
init_sanic()=初始化sanic Web框架
class ForcedShutdown(Exception):
"""
Custom exception to be raised
"""
pass
def signal_handler(signal, frame):
print(f'signal received is {signal}')
raise ForcedShutdown
if(__name__ == '__main__'):
try:
signal.signal(signal.SIGINT, signal_handler)
client = DiscordBot()
bot_thread = Thread(target=lambda : client.run(setup_pars['CLIENT_TOKEN']))
api_thread = Thread(target=lambda : init_sanic())
threads = [api_thread, bot_thread]
for x in threads:
x.start()
while True:
time.sleep(100)
except (ForcedShutdown, SystemExit):
print('DO SHUTDOWN ACTIONS')
输出:
[2019-07-31 19:49:18 +0100] [11808] [DEBUG]
Sanic
Build Fast. Run Fast.
[2019-07-31 19:49:18 +0100] [11808] [INFO] Goin' Fast @ http://0.0.0.0:8000
[2019-07-31 19:49:18 +0100] [11808] [WARNING] Sanic tried to use loop.add_signal_handler but it is not implemented on this platform.
[2019-07-31 19:49:18 +0100] [11808] [WARNING] Sanic tried to use loop.add_signal_handler but it is not implemented on this platform.
[2019-07-31 19:49:18 +0100] [11808] [INFO] Starting worker [11808]
Discord Bot Loaded
用于发送信号的代码:
import os
import signal
os.kill(pid, signal.SIGINT)
最终输出:
Process finished with exit code 2
代码按预期退出时,输出为:
[2019-07-31 19:49:18 +0100] [11808] [DEBUG]
Sanic
Build Fast. Run Fast.
[2019-07-31 19:49:18 +0100] [11808] [INFO] Goin' Fast @ http://0.0.0.0:8000
[2019-07-31 19:49:18 +0100] [11808] [WARNING] Sanic tried to use loop.add_signal_handler but it is not implemented on this platform.
[2019-07-31 19:49:18 +0100] [11808] [WARNING] Sanic tried to use loop.add_signal_handler but it is not implemented on this platform.
[2019-07-31 19:49:18 +0100] [11808] [INFO] Starting worker [11808]
Discord Bot Loaded
Process finished with exit code 2
预期的最终输出是:
[2019-07-31 19:49:18 +0100] [11808] [DEBUG]
Sanic
Build Fast. Run Fast.
[2019-07-31 19:49:18 +0100] [11808] [INFO] Goin' Fast @ http://0.0.0.0:8000
[2019-07-31 19:49:18 +0100] [11808] [WARNING] Sanic tried to use loop.add_signal_handler but it is not implemented on this platform.
[2019-07-31 19:49:18 +0100] [11808] [WARNING] Sanic tried to use loop.add_signal_handler but it is not implemented on this platform.
[2019-07-31 19:49:18 +0100] [11808] [INFO] Starting worker [11808]
Discord Bot Loaded
DO SHUTDOWN ACTIONS
Process finished with exit code 2
感谢您的帮助!