python - Python 3.4 中的 “async with”

标签 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:

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

最佳答案

我去做了,这对我有用。

@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='')

关于python - Python 3.4 中的 “async with”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47988109/

相关文章:

python - 我如何操作列表?

python - 如何使用 json 文件使用 url lib

python - 带输入检查的 If 语句输出不正确

django - python 3中的S3BotoStorage

python - 连续调用时ElasticSearch不会返回匹配-Python

python-3.7 - python3.7+中是否有任何默认的异步空上下文管理器?

Python异步: Unable to run parallel asynio couroutine

python - 在 boto3 中使用 RDS 标签/如何在 boto3 中获取 ARN

python - 如何将列合并到新表中 - Python 或 R

python-3.6 - 有没有办法判断 asyncio 事件循环是否满负荷?