python - Await Doesn't Work with Coroutine Assigned to Variable?
问题描述
Why in Python (3.6) does
chunk = await evt_loop.run_in_executor(io_exec, arc.read, chunk_size)
work exactly as expected but
read_ftr = evt_loop.run_in_executor(io_exec, arc.read, chunk_size)
chunk = await read_ftr
throws AssertionError("yield from wasn't used with future",) on the second line, and how do I get it to work?
The following is the snippet of code I'm trying to run. Fusing the three read_ftr lines together to get the first single-line implementation works, while the way it is below throws that assertion error at "chunk = await read_ftr".
read_ftr: aio.Future = None
hash_ftr: aio.Future = None
chunk = None
with open(arc_path, "rb") as arc:
while arc_offs < arc_size:
chunk_size = min(arc_size - arc_offs, max_chunk_size)
if read_ftr:
chunk = await read_ftr
read_ftr = evt_loop.run_in_executor(io_exec, arc.read, chunk_size)
arc_offs += chunk_size
if not chunk:
continue
if hash_ftr:
await hash_ftr
hash_ftr = hasher.async_update(chunk)
if hash_ftr:
await hash_ftr
await hasher.async_digest()
解决方案
当你像你一样声明一个变量时,你foo_var = coroutine(args)
实际上是在调用函数并将其结果应用于变量。要将函数作为变量传递,请执行此操作foo_var = coroutine
,然后在foo_var(args)
任何时候在函数旁边添加括号时调用它,它将尝试调用并运行该函数(即使它是协程/异步函数)
推荐阅读
- java - 如何让我的应用程序永远运行,即使在后台
- amazon-web-services - 如何在 AWS Fargate 上运行 puppeteer?
- javascript - 在 getDerivedStateFromProps 中访问上下文
- sql - 使用在其他字段中具有匹配值的其他记录字段更新记录的字段
- flutter - 为什么我的 FAB 刷新按钮在 WebView 中点击时不刷新?
- mysql - MySQL - 根据包含 where 子句的另一个列值选择特定列
- sql - 基于参数的select语句中的条件列
- java - Java Android 应用布局崩溃 - 使用 CoordinatorLayout 和 Fragment
- php - 需要帮助通过 url 将两个 php 变量传递到下一页
- xpath - ImportXML 和 ImportJSON 不起作用。如何从动态网站导入数据?