python - Python:Concurrent.Futures 错误 [TypeError:'NoneType' 对象不可调用]
问题描述
所以我设法让 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))
我的错误可以追溯到“for response in await asyncio.gather(*futures):”
供您参考,搜索(查询)只是我的 Google CSE API 调用的函数。
解决方案
问题在于调用run_in_executor
:
futures = [
loop.run_in_executor(
executor,
searching(queries)
)
]
run_in_executor
接受要执行的函数。代码不会将函数传递给它,而是调用函数searching
,然后传递run_in_executor
该调用的返回值。这有两个后果:
代码没有按预期工作——它一个接一个地调用搜索,而不是并行调用;
它显示一个错误,抱怨尝试
run_in_executor
调用 . 的None
返回值searching(...)
。令人困惑的是,该错误只是在稍后等待返回的期货时才出现run_in_executor
,此时所有搜索实际上都已完成。
正确的调用方式run_in_executor
如下:
futures = [
loop.run_in_executor(executor, searching, queries)
]
请注意该searching
功能现在只被提及而不是被使用。
此外,如果您只使用 asyncio 来调用 中的同步调用run_in_executor
,那么您并没有真正从它的使用中受益。您可以直接使用基于线程的工具获得相同的效果concurrent.futures
,但无需将整个程序调整为 asyncio。run_in_executor
旨在谨慎使用,用于偶尔与不提供异步前端的遗留 API 接口,或用于无法有意义地转换为协程的 CPU 密集型代码。
推荐阅读
- swift - SwiftUI:从后台返回后激活显示时应用程序崩溃
- python - python string.whitespace中的空字符串
- sqlite - CakePHP 使用 Sqlite 而不是 Mysql
- macos - Hadoop 在启动时崩溃 - docker-compose (MacOS)
- arrays - 两个 1D numpy / torch 数组的特殊索引以生成另一个数组
- reactjs - Page 404 appears in all routes of React Router
- javascript - How to have a fallback like behavior for static export in Next.JS
- java - Are creational design patterns useless in Dependency Injection environment ( like SpringBoot)?
- docusignapi - Submit DocuSign PowerForms
- bash - How to delete a folder by parameter and protect by user bugs/errors