[英]Unable to quit from python script using CTRL+C in Win10
With the following code I'm unable to quit using CTRL+C after running it.使用以下代码,我无法在运行后使用 CTRL+C 退出。 I also tried to catch KeyboardInterrupt
from different code positions without success.我还尝试从不同的代码位置捕获KeyboardInterrupt
,但没有成功。 I'm using Windows 10 x64 and Python 3.7.6.我正在使用 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()
your using exception for the keyboard interruptions so try import sys and following lines您对键盘中断的使用例外,因此请尝试 import 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()
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.