从同步代码调用Python3.4.3异步基础设施的异步函数
aioawait的Python项目详细描述
这个包在上面实现了两个原语(await和spawn) python 3的异步基础设施。这两个函数允许我们调用 同步代码中的异步函数。
安装
pip3 install aioawait
示例
fromasyncio.tasksimportcoroutine,sleep,asyncfromaioawaitimportawait,spawn@coroutinedefmonitor(name,size,total):whileTrue:print('\ttotal',name,total)yield fromsleep(1)@coroutinedefcounter(name,size,total):"""sums into total all numbers from 0 to size"""m=async(monitor(name,size,total))# monitor could be called using spawn. eg:# m = spawn(monitor(name, size, total))forninrange(size):total[0]+=nifn%5==0:print('sleeping',name,n)yield fromsleep(2)else:print('counting',name,n)yield# stops monitorm.cancel()returnname,'done',n,totalclassCounter:"""note that this class has no asynchronous code"""def__init__(self):self.cb=spawn(counter('b',40,[0]))@propertydefcounter_a(self):returnawait(counter('a',20,[0]))@propertydefcounter_b(self):returnawait(self.cb)if__name__=='__main__':c=Counter()print(c.counter_a)print(c.counter_b)