我从异步进程退出时出现问题,该进程由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('无法关闭正在运行的事件循环',)> Traceback(最近一次调用最后一次):文件“/usr/lib/python3.5/asyncio/tasks.py”,行239,在_step结果= coro.send(无)文件“FTPclient.py”,第54行,在recieve_data中await 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:无法关闭正在运行的事件循环
我将非常感谢您的帮助,并提前感谢您!