python异步_异步-同步-在一个python事件循环中异步调用

Come on! It makes you change all your project because of one asyncio

usage. Tell me this is not true.

这是真的 :)

使用await关键字的整个想法是在一个事件循环中从代码的不同位置执行并发作业(这对于常规功能代码是无法做到的).

asyncio-不是某种实用程序,而是编写异步程序的整体风格.

另一方面,Python非常灵活,因此您仍然可以尝试隐藏asyncio的使用.如果您确实想要获取3个Fetcher实例的同步结果,则可以执行以下操作:

import asyncio

def sync_exec(coro):

loop = asyncio.get_event_loop()

return loop.run_until_complete(coro)

class Fetcher:

async def async_get_result(self):

# async interface:

async def async_job():

await asyncio.sleep(1)

return id(self)

return (await async_job())

def get_result(self):

# sync interface:

return sync_exec(self.async_get_result())

@classmethod

def get_results(cls, *fetchers):

# sync interface multiple:

return sync_exec(

asyncio.gather(*[fetcher.async_get_result() for fetcher in fetchers])

)

# single sync get_result:

f1 = Fetcher()

print('Result: ', f1.get_result())

# multiple sync get_result:

f2 = Fetcher()

f3 = Fetcher()

print('Results: ', Fetcher.get_results(f1, f2, f3))

输出:

Result: 2504097887120

Results: [2504097887120, 2504104854416, 2504104854136]

但是,再次重申,相信您,如果有一天继续以这种方式编写代码,您将真的后悔.如果要充分利用异步编程的优势,请使用协程并显式等待.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值