【发布时间】:2018-05-02 18:01:29
【问题描述】:
在 Python 3.6 中,我可以在协程中使用 yield。但是我无法使用yield from。
下面是我的代码。在第 3 行,我等待另一个协程。在第 4 行,我尝试 yield from 一个文件。为什么 Python 3.6 不允许我这样做?
async def read_file(self, filename):
with tempfile.NamedTemporaryFile(mode='r', delete=True, dir='/tmp', prefix='sftp') as tmp_file:
await self.copy_file(filename, tmp_file)
yield from open(tmp_file)
以下是 Python 3.6 为上述代码引发的异常:
File "example.py", line 4
yield from open(tmp_file)
^
SyntaxError: 'yield from' inside async function
【问题讨论】:
-
是否可以使用 @asyncio.coroutine 装饰器在异步函数中启用“yield from”?来自 asyncio 文档:“@asyncio.coroutine¶ 装饰器来标记基于生成器的协程。这使生成器能够使用 yield from 来调用 async def 协程,并且还使生成器能够被 async def 协程调用,例如使用 await表达。”我不确定这是否适用于您上面编写的代码...
标签: python python-3.x async-await python-3.6 python-asyncio