在使用标准库时,我发现 python2 和 python3 之间有一个奇怪的区别。如果我在 TCPServer 在不同的线程中运行时尝试在 python2 中捕获信号,则不会处理该信号,但在 python3 中却可以。
这是重现问题的脚本
import signal
import threading
import sys
if sys.version_info > (3,0):
from socketserver import TCPServer, BaseRequestHandler
else:
from SocketServer import TCPServer, BaseRequestHandler
def shutdown(signum, frame):
print("Shutting down server thread")
server.shutdown()
server = TCPServer(
('127.0.0.1', 7654),
BaseRequestHandler
)
signal.signal(signal.SIGTERM, shutdown)
signal.signal(signal.SIGINT, shutdown)
server_thread = threading.Thread(target=server.serve_forever)
print("Starting server thread")
server_thread.start()
print("Waiting for server thread to shut down")
server_thread.join()
print("Server thread terminated")
这是 python3 的输出:
Starting server thread
Waiting for server thread to shut down
^CShutting down server thread
Server thread terminated
这是来自python2:
Starting server thread
Waiting for server thread to shut down
^CKilled
“^C”是键盘中断,“Killed”是我发送给进程的 sigkill。
为什么不调用关机?