使用以下代码后,我无法退出使用CTRL+C。我还试图从不同的代码位置捕获KeyboardInterrupt
,但没有成功。我使用的是Windows 10 x64和Python 3.7.6。
async def handle_req(self, reader: StreamReader, writer: StreamWriter):
try:
data = await reader.read()
msg = data.decode()
addr = writer.get_extra_info('peername')
print(f"Received {msg!r} from {addr!r}")
writer.write("Res".encode())
writer.write_eof()
await writer.drain()
writer.close()
except OSError:
print("Client endpoint unreachable")
async def main():
try:
server = await asyncio.start_server(handle_req, "127.0.0.1", 9000)
addr = server.sockets[0].getsockname()
print(f'Serving on {addr}')
async with server:
await server.serve_forever()
except KeyboardInterrupt:
server.close()
server.wait_closed()
raise
if __name__ == '__main__':
try:
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
except KeyboardInterrupt:
loop.stop()
loop.close()
您对键盘中断的使用异常,请尝试导入sys和以下行
import sys
if __name__ == '__main__':
try:
loop = asyncio.get_event_loop()
loop.run_until_complete(main())
except KeyboardInterrupt:
loop.stop()
loop.close()
sys.exit()