我在退出由asyncio处理的异步过程时遇到问题。这是ftp服务器+客户端项目,我要在执行 exit 命令后终止客户端进程。
此代码最重要的部分在这里:
class FtpCommandsReceiver:
def __init__(self, loop, sock):
self.loop = loop
self.sock = sock
self.loop.create_task(self.recieve_data())
self.commands_to_handle = {
'exit': self.exit_handler
}
async def recieve_data(self):
while True:
self.data_to_send = input('ftp> ')
if self.data_to_send == '':
continue
await self.loop.sock_sendall(self.sock, self.data_to_send.encode())
try:
await self.commands_to_handle.get(self.data_to_send)()
except TypeError:
pass
self.received_data = await self.loop.sock_recv(self.sock, 10000)
print(self.received_data.decode())
if not self.received_data:
break
print('Connection closed by the server')
self.sock.close()
async def exit_handler(self):
self.loop.stop()
self.loop.close()
if __name__ == '__main__':
loop = asyncio.get_event_loop()
FTP_connection = FtpConnection(loop)
task = loop.create_task(FTP_connection.connect())
try:
loop.run_forever()
finally:
loop.close()
调用 exit_handler 方法时,会引发异常:
从未检索到任务异常
未来:exception = RuntimeError('无法关闭正在运行的事件循环',)> 追溯(最近一次通话):
_step中的文件“ /usr/lib/python3.5/asyncio/tasks.py”,第239行 结果= coro.send(无)
文件“ FTPclient.py”,第54行,位于recieve_data中 等待self.commands_to_handle.get(self.data_to_send)()
文件“ FTPclient.py”,第66行,位于exit_handler中 self.loop.close()
关闭文件“ /usr/lib/python3.5/asyncio/unix_events.py”,第56行 super()。close()
关闭文件“ /usr/lib/python3.5/asyncio/selector_events.py”,第94行 引发RuntimeError(“无法关闭正在运行的事件循环”)
RuntimeError:无法关闭正在运行的事件循环
感谢您的帮助,在此先感谢您!