5

在使用标准库时,我发现 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。

为什么不调用关机?

4

1 回答 1

4

对我来说,似乎 thread.join() 做了一些锁定并阻止捕获信号。

我已经在 Python 2.7 中测试了以下代码,它似乎可以工作:

import time
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.running = False
    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()
server.running = True
print("Waiting for server thread to shut down")

while server.running:
    time.sleep(1)

server_thread.join()
print("Server thread terminated")
于 2012-06-07T07:58:08.610 回答