简体   繁体   English

从python的协程对象中检索数据

[英]Retrieving data from python's coroutine object

I am trying to learn async, and now I am trying to get whois information for a batch of domains.我正在尝试学习异步,现在我正在尝试获取一批域的 whois 信息。 I found this lib aiowhois , but there are only a few strokes of information, not enough for such newbie as I am.我找到了这个 lib aiowhois ,但是只有几笔信息,对于我这样的新手来说还不够。

This code works without errors, but I don't know how to print data from parsed whois variable, which is coroutine object.这段代码可以正常工作,但我不知道如何从解析的whois变量(协程对象)打印数据。

resolv = aiowhois.Whois(timeout=10)

async def coro(url, sem):
    parsed_whois = await resolv.query(url)

async def main():
    tasks = []
    sem = asyncio.Semaphore(4)

    for url in domains:
        task = asyncio.Task(coro(url, sem))
        tasks.append(task)
    await asyncio.gather(*tasks)

loop = asyncio.get_event_loop()
loop.run_until_complete(main())

You can avoid using tasks.您可以避免使用任务。 Just apply gather to the coroutine directly.直接将 gather 应用到协程即可。 In case you are confused about the difference, this SO QA might help you (especially the second answer).如果您对差异感到困惑,这个SO QA可能会帮助您(尤其是第二个答案)。

You can have each coroutine return its result, without resorting to global variables:您可以让每个协程返回其结果,而无需求助于全局变量:

async def coro(url):
    return await resolv.query(url)

async def main():
    domains = ...
    ops = [coro(url) for url in domains]
    rets = await asyncio.gather(*ops)
    print(rets)

Please see the official docs to learn more about how to use gather or wait or even more options请参阅官方文档以了解有关如何使用gatherwait甚至更多选项的更多信息

Note: if you are using the latest python versions, you can also simplify the loop running with just注意:如果您使用的是最新的 python 版本,您还可以简化循环运行

asyncio.run(main())

Note 2: I have removed the semaphore from my code, as it's unclear why you need it and where.注 2:我已经从我的代码中删除了信号量,因为不清楚您为什么需要它以及在哪里需要它。

all_parsed_whois = []  # make a global

async def coro(url, sem):
    all_parsed_whois.append(await resolv.query(url))

If you want the data as soon as it is available you could task.add_done_callback()如果您希望数据一可用,您可以 task.add_done_callback()

python asyncio add_done_callback with async def python asyncio add_done_callback with async def

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM