Python 3.4中的“异步”

时间:2017-12-27 07:28:04

标签: python python-3.4 python-asyncio

asyncssh的入门文档提供了以下hello示例:

import asyncio, asyncssh, sys

async def run_client():
    async with asyncssh.connect('localhost') as conn:
        result = await conn.run('echo "Hello!"', check=True)
        print(result.stdout, end='')

try:
    asyncio.get_event_loop().run_until_complete(run_client())
except (OSError, asyncssh.Error) as exc:
    sys.exit('SSH connection failed: ' + str(exc))

但是,这不会运行,因为Python 3.4不支持异步:

async with asyncssh.connect('localhost', username='squirtle', password='xxxxxxxxxxxx') as conn:
     ^

2 个答案:

答案 0 :(得分:2)

我去做了,这适合我。

@asyncio.coroutine
def run_client():
        with(yield from asyncssh.connect('localhost', username='root', password='xxxxxxxx')) as conn:
                result = yield from conn.run('ls', check=True)
                print(result.stdout, end='')

答案 1 :(得分:2)

Python 3.5 中引入了

async关键字,您应该在早期版本中使用asyncio.corutine

检查PEP492Python 3.5 release notes

此外,您还要查看此SO Question and answers