【发布时间】:2020-06-01 00:21:45
【问题描述】:
import time
import asyncio
import aiohttp
async def is_name_available(s, name):
async with s.get("https://twitter.com/%s" % name) as res:
if res.raise_for_status == 404:
print('%s is available!' % name)
return name
async def check_all_names(names):
async with aiohttp.ClientSession(raise_for_status=True) as s:
tasks = []
for name in names:
task = asyncio.create_task(is_name_available(s, name))
tasks.append(task)
return await asyncio.gather(*tasks)
def main():
with open('names.txt') as in_file, open('available.txt', 'w') as out_file:
names = [name.strip() for name in in_file]
start_time = time.time()
results = asyncio.get_event_loop().run_until_complete(check_all_names(names))
results = [i for i in results if i]
out_file.write('\n'.join(results))
print(f'[ <? ] Checked {len(names)} words in {round(time.time()-start_time, 2)} second(s)')
if __name__ == '__main__':
main()
我似乎无法弄清楚如何使用我在另一个项目中使用的这个 asyncio/aiohttp 结构在 is_name_available 中仅返回 404 链接。我是 python 的初学者,不胜感激。
【问题讨论】:
-
除了您得到的出色答案之外,您还可以使用
asyncio.run(check_all_names(names))而无需明确获取事件循环 -
请不要通过破坏您的帖子为他人增加工作量。通过在 Stack Exchange 网络上发帖,您已在 CC BY-SA 4.0 license 下授予 Stack Exchange 分发该内容的不可撤销的权利(即无论您未来的选择如何)。根据 Stack Exchange 政策,帖子的非破坏版本是分发的版本。因此,任何破坏行为都将被撤销。如果您想了解更多关于删除帖子的信息,请参阅:How does deleting work?
标签: python-3.x python-asyncio aiohttp