什么是“异步_生成器”&它与Python3.6中的“协同程序”有何不同?

2024-09-29 00:13:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我怀疑这与b/w{}的差异有关&await。 然而,;除了新对象被指定为async_generator之外,我还不清楚它与coroutine之间的区别。 (除了我在标题中提出的问题外,我不知道还有什么其他问题可以问…)

import asyncio

async def async_generator_spits_out_letters():
    yield 'a'
    yield 'b'
    yield 'c'
    yield 'd'
    await asyncio.sleep(0)

async def coroutine_prints_messages():
    while True:
        print('hi')
        await asyncio.sleep(2)

def test_it():
    print(type(async_generator_spits_out_letters))
    print(type(coroutine_prints_messages))
    # This is how I choose to do newlines....it's easier for me to read. :[
    print(); print()

    print(type(async_generator_spits_out_letters()))
    print(type(coroutine_prints_messages()))

这使得:

<class 'async_generator'>
<class 'coroutine'>


<class 'function'>
<class 'function'>

我对这件事一无所知


Tags: asyncioasyncdeftypeawaitoutgeneratorprints
1条回答
网友
1楼 · 发布于 2024-09-29 00:13:49

为了使一个async_generator产生函数在eventloop中运行,它的输出必须包装在一个coroutine.

这是为了防止async_generator直接在事件循环中产生值。


import asyncio

# This produces an async_generator
async def xrange(numbers):
    for i in range(numbers):
        yield i
        await asyncio.sleep(0)

# This prevents an async_generator from yielding into the loop.
async def coroutine_wrapper(async_gen, args):
    try:
        print(tuple([i async for i in async_gen(args)]))
    except ValueError:
        print(tuple([(i, j) async for i, j in async_gen(args)]))

循环仅类似于任务&;未来

如果循环从其任务之一接收到整数或字符串或..任何不是从future派生的内容,它将中断

因此coroutines必须:

  • 产生futures(或future的子类)
  • 或者不将任何值传递回循环

这里是main()

def main():
    print('BEGIN LOOP:')
    print()
    loop = asyncio.get_event_loop()
    xrange_iterator_task = loop.create_task(coroutine_wrapper(xrange, 20))
    try:
        loop.run_until_complete(xrange_iterator_task)
    except KeyboardInterrupt:
        loop.stop()
    finally:
        loop.close()
    print()
    print('END LOOP')
    print(); print()
    print('type(xrange) == {}'.format(type(xrange)))
    print('type(xrange(20) == {}'.format(type(xrange(20))))
    print()
    print('type(coroutine_wrapper) == {}'.format(type(coroutine_wrapper)))
    print('type(coroutine_wrapper(xrange,20)) == {}'.format(type(coroutine_wrapper(xrange, 20))))
if __name__ == '__main__':
    main()

以下是输出:

BEGIN LOOP:

(0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19)

END LOOP


type(xrange) == <class 'function'>
type(xrange(20)) == <class 'async_generator'>

type(coroutine_wrapper) == <class 'function'>
type(coroutine_wrapper(xrange,20)) == <class 'coroutine'>

相关问题 更多 >