python3 - 从异步方法中获取结果 [英] python3 -Get result from async method

查看:100
本文介绍了python3 - 从异步方法中获取结果的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是 Python 的新手.我使用 asyncio 编写了一个简单的报废程序.这是我的代码片段

I am a newbie to Python. I have written a simple scrapping program using asyncio. Here are my code snippets

 loop = asyncio.get_event_loop()
 task = loop.create_task(conSpi.parse(arguments.url))
 value = loop.run_until_complete(asyncio.wait([task]))
 loop.close()

我想打印以值返回的结果.而不是打印变量的值,它打印这样的东西

I want to print result being returned in value.Rather printing variable's value, it prints something like this

 {<Task finished coro=<ConcurrentSpider.parse() done, 
 defined at /home/afraz/PycharmProjects/the-lab/concurrentspider.py:28> result=3>}

`

我怎样才能只得到结果而不打印休息?

How can I get the result only and not get rest printed?

推荐答案

最简单的方法就是写

value = loop.run_until_complete(task)

这仅在您想等待一项任务时有效.如果您需要多个任务,则需要正确使用 asyncio.wait.它返回一个包含已完成和未决期货的元组.但默认情况下,挂起的期货将为空,因为它会等待所有期货完成.

That only works if you want to wait on one task. If you need more than one task, you'll need to use asyncio.wait correctly. It returns a tuple containing completed and pending futures. By default though, the pending futures will be empty because it waits for all futures to complete.

有点像

done, pending = loop.run_until_complete(asyncio.wait( tasks))
for future in done:
    value = future.result() #may raise an exception if coroutine failed
    # do something with value

这篇关于python3 - 从异步方法中获取结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆