【发布时间】:2021-12-17 16:07:49
【问题描述】:
鉴于我仍在学习一般的异步编程,如果这个问题太基本了,我深表歉意。 我想对使用 Python 的公司列表进行 Google 搜索。因为列表中有超过 20,000 家公司,我想异步执行这些操作。我尝试使用 Python 中的 asyncio 库执行此操作,但我无法让它工作,它仍然同步运行超过 4 小时。 如何使下面的代码异步运行?
当我运行这个时:
from googlesearch import search
import asyncio
companies = [
'Apple',
'Google',
'Tesla'
]
async def gsearch(company):
return search(company, num=3, stop=3)
async def make_gsearch(company):
print(f"Searching {company}")
search_res = await gsearch(company)
print(f"Done with {company}")
return list(search_res)
async def run_search():
return await asyncio.gather(*[make_gsearch(company) for company in companies])
asyncio.run(run_search())
我得到这个输出:
Searching Apple
Done with Apple
Searching Google
Done with Google
Searching Tesla
Done with Tesla
但我想让它在等待其他搜索结果返回时开始每次搜索。这将产生类似:
Searching Apple
Searching Google
Searching Tesla
Done with Apple
Done with Google
Done with Tesla
任何帮助表示赞赏, 谢谢
【问题讨论】:
-
你考虑过多线程吗?它更容易(恕我直言)并且完全适合您的需求
-
问题是
sesrch仍然是一个阻塞调用。你要么需要切换到 asyncio 感知的东西,要么按照上面的建议使用 concurrent.futures。 -
感谢您的 cmets!我有2万家公司,启动2万线程可以吗?
标签: python python-asyncio