循环遍历多个async_generator对象

时间:2018-02-24 12:48:12

标签: python asynchronous

我开始解决一些问题来掌握python asyncio模块。我想要创建的是一个'时钟',它基本上只打印出程序启动后的时间:小时:分钟:第二格式。我想过制作三个async_generator并在一个单独的异步方法中使用for循环遍历这三个async_generators。使用builtin zip()方法给我带来以下错误。

TypeError: zip argument #1 must support iteration

代码:

import asyncio

second = 1

async def seconds():
    while True:
        for i in range(1,61):
            await asyncio.sleep(second)
            yield i

async def minutes():
    while True:
        for i in range(1,61):
            await asyncio.sleep(60*second)
            yield i

async def hours():
    while True:
        for i in range(1,61):
            await asyncio.sleep(60*60*second)
            yield i

async def clock():
    for s,m,h in zip(seconds(),minutes(),hours()):
        print('{0}:H{1}:M{2}:S'.format(h,m,s))

if __name__ == '__main__':
    loop = asyncio.get_event_loop()
    loop.run_until_complete(clock())

我的问题是,async_genertator对象不支持迭代吗?当我检查时,我可以看到async_generator对象hours()有____aiter____方法。是不是____aiter____可迭代?我写的代码有什么问题。

0 个答案:

没有答案