Isa*_*Lau 4 python typeerror nonetype python-asyncio
所以我设法让 asyncio / Google CSE API 一起工作......当我在 PyCharm 上运行我的代码时,我能够打印我的结果。然而,在打印内容的最后是错误“TypeError: 'NoneType' object is not callable”。
我怀疑这与我的列表有关,也许循环试图搜索另一个术语,即使我位于列表的末尾......
另外..这是我的第一个问题帖子,所以请随时提供有关如何更好地提出问题的建议
想法?
searchterms = ['cheese',
'hippos',
'whales',
'beluga']
async def sendQueries(queries, deposit=list()):
with concurrent.futures.ThreadPoolExecutor(max_workers=4) as executor:
loop = asyncio.get_event_loop()
futures = [
loop.run_in_executor(
executor,
searching(queries)
)
]
for response in await asyncio.gather(*futures):
deposit.append(response.json())
return deposit
def running():
loop = asyncio.get_event_loop()
loop.run_until_complete(loop.create_task(sendQueries(searchterms)))
loop.close()
print(running())
print(str(time.time() - x))
Run Code Online (Sandbox Code Playgroud)
我的错误可以追溯到“等待 asyncio.gather(*futures) 中的响应:”
供您参考,搜索(查询)只是我的 Google CSE API 调用的函数。
问题出在对以下内容的调用中run_in_executor:
futures = [
loop.run_in_executor(
executor,
searching(queries)
)
]
Run Code Online (Sandbox Code Playgroud)
run_in_executor接受要执行的函数。该代码不会向其传递函数,而是调用函数,searching并传递run_in_executor该调用的返回值。这有两个后果:
该代码没有按预期工作 - 它依次调用搜索,而不是并行;
它显示一个错误,抱怨尝试run_in_executor调用None的返回值searching(...)。令人困惑的是,只有在等待返回的 future 时才会引发错误run_in_executor,此时所有搜索实际上都已经完成。
正确的调用方法run_in_executor是这样的:
futures = [
loop.run_in_executor(executor, searching, queries)
]
Run Code Online (Sandbox Code Playgroud)
请注意该searching函数现在仅被提及而不是被使用。
另外,如果您仅使用 asyncio 来调用 中的同步调用run_in_executor,那么您并没有真正从它的使用中受益。您可以直接使用基于线程的工具获得相同的效果concurrent.futures,但无需将整个程序调整为 asyncio。run_in_executor应该谨慎使用,要么用于偶尔与不提供异步前端的遗留 API 进行交互,要么用于无法有意义地转换为协程的 CPU 密集型代码。
| 归档时间: |
|
| 查看次数: |
8019 次 |
| 最近记录: |