TypeError:需要Future或协程

kol*_*lko 5 python python-asyncio

我尝试在asyncssh上进行自动重新连接ssh客户端。(SshConnectManager必须留在后台并在需要时进行ssh会话)

class SshConnectManager(object):
def __init__(self, host, username, password, port=22):
    self._host = host
    self._username = username
    self._password = password
    self._port = port

    self.conn = None
    asyncio.async(self.start_connection)

@asyncio.coroutine
def start_connection(self):
    try:
        Client = self._create_ssh_client()
        self.conn, _ = yield from asyncssh.create_connection(Client,
                                                        self._host, port=self._port,
                                                        username=self._username,
                                                        password=self._password)
    except Exception as e:
        print("Connection error! {}".format(e))
        asyncio.async(self.start_connection())

def _create_ssh_client(self):
    class MySSHClient(asyncssh.SSHClient):
        parent = self
        def connection_lost(self, exc):
            self.parent._handle_connection_lost(exc)
    return MySSHClient

def _handle_connection_lost(self, exc):
    print('Connection lost on {}'.format(self.host))
    print(exc)
    asyncio.async(self.start_connection)


ssh1 = SshConnectManager(settings.host, settings.username, settings.password, settings.port)

asyncio.get_event_loop().run_until_complete(...)
Run Code Online (Sandbox Code Playgroud)

请不要看_create_ssh_client或其他“哈希”

问题是:

$ python3 main.py 
Traceback (most recent call last):
  File "main.py", line 75, in <module>
    ssh1 = SshConnectManager(settings.host, settings.username, settings.password, settings.port)
  File "main.py", line 22, in __init__
    asyncio.async(self.start_connection)
  File "/usr/lib/python3.4/asyncio/tasks.py", line 565, in async
    raise TypeError('A Future or coroutine is required')
TypeError: A Future or coroutine is required
Run Code Online (Sandbox Code Playgroud)

但是self.start_connection是轻率的!或不?或从同步代码开始异步任务的另一种方法是什么?

kol*_*lko 2

感谢@dano 和@boardrider 在评论中提供帮助。Bug 是 @asyncio.coroutine 返回函数需要调用什么来获取生成器对象。我忘记这样做了。

固定版本:

class SshConnectManager(object):
def __init__(self, host, username, password, port=22):
    self._host = host
    self._username = username
    self._password = password
    self._port = port

    self.conn = None
    # FIX HERE
    asyncio.async(self.start_connection())

@asyncio.coroutine
def start_connection(self):
    try:
        Client = self._create_ssh_client()
        self.conn, _ = yield from asyncssh.create_connection(Client,
                                                        self._host, port=self._port,
                                                        username=self._username,
                                                        password=self._password)
    except Exception as e:
        print("Connection error! {}".format(e))
        asyncio.async(self.start_connection())

def _create_ssh_client(self):
    class MySSHClient(asyncssh.SSHClient):
        parent = self
        def connection_lost(self, exc):
            self.parent._handle_connection_lost(exc)
    return MySSHClient

def _handle_connection_lost(self, exc):
    print('Connection lost on {}'.format(self.host))
    print(exc)
    # AND HERE
    asyncio.async(self.start_connection())


ssh1 = SshConnectManager(settings.host, settings.username, settings.password, settings.port)

asyncio.get_event_loop().run_until_complete(...)
Run Code Online (Sandbox Code Playgroud)

PS但我不明白为什么协程装饰器不能返回调用装饰器。(这让我很困惑,我将其与扭曲的回调混淆了)。

我找到了如何记住这一点,有简单的情况,如果 start_connection 可以获取参数:

@asyncio.coroutine
def start_connection(self, some_arg):
    pass
Run Code Online (Sandbox Code Playgroud)

所以,我可以简单地写:

asyncio.async(self.start_connection(some_val))
Run Code Online (Sandbox Code Playgroud)

并且不需要在 asyncio.async 函数中添加额外的属性