大家好,我学习异步编程的时候,遇到下面的这段代码:
[Python] 纯文本查看 复制代码 from threading import Thread
import socket
class ClientEchoThread(Thread):
def __init__(self, client):
super().__init__()
self.client = client
def run(self):
try:
while True:
data = self.client.recv(2048)
if not data: #A
raise BrokenPipeError('Connection closed!')
print(f'Received {data}, sending!')
self.client.sendall(data)
except OSError as e: #B
print(f'Thread interrupted by {e} exception, shutting down!')
def close(self):
if self.is_alive(): #C
self.client.sendall(bytes('Shutting down!', encoding='utf-8'))
self.client.shutdown(socket.SHUT_RDWR) #D
with socket.socket(socket.AF_INET, socket.SOCK_STREAM) as server:
server.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
server.bind(('127.0.0.1', 8000))
server.listen()
connection_threads = []
try:
while True:
connection, addr = server.accept()
thread = ClientEchoThread(connection)
connection_threads.append(thread)
thread.start()
except KeyboardInterrupt:
print('Shutting down!')
[thread.close() for thread in connection_threads] #E
当运行环境是windows,在cmd中python 运行它,启动后在命令行中无法输入CTRL+C。
但是如果换成下面的代码就可以正常捕获键盘中断信号。
[Python] 纯文本查看 复制代码 import time
def main():
print('before ...')
time.sleep(20)
print('after ...')
if __name__ == '__main__':
try:
main()
except KeyboardInterrupt:
print('\nKeyboardInterrupt ...')
print('the end')
请问为什么第一段程序无法捕捉到键盘中断信号CTRL+C了?该如何改写在 try 中的循环中能触发 KeyboardInterrupt 了?
|