Python 协程

2019-12-27
1分钟阅读时长

yield

当函数中有 yield 时,运行该函数不会运行,而会返回一个<generator object>。

使用 next(func_ret_object) 将函数运行至第一个 yield 处。

使用 w = func_ret_object.send(value) 将数据传入处,并且获得的返回值存入 w。

def yield_test():
    count = 0                           # 2
    while True:                         # 2, 4, 6
        print(f'start loop: {count}')   # 2, 4, 6
        number = yield 'return to out'  # 2, 4, 6
        # yield 后面是返回给外面的,前面是由 send 传入的
        print(f'yield: {number}')       # 4, 6
        count += 1

y = yield_test()
print('--before next--')       # 1
w = y.send(None)               # 2
# 等价于 w = next(y)
print('--after next--')        # 3
next(y)                        # 4
print('--------------')        # 5
ret = y.send('give function')  # 6
print(ret)                     # 7

async, await

async def 定义一个函数

import asyncio

async def test1():
    while True:
        # 这里一定要有等待的函数用于切换,不然会一直运行这里
        # 不能使用 time.sleep()
        # 也可以 await 一个 async 的函数
        await asyncio.sleep(4)
        print('test1')

async def test2():
    while True:
        await asyncio.sleep(3)
        print('test2')


loop = asyncio.get_event_loop()
tasks = [
    test1(),
    test2(),
]
print('start async')
# 这里开始运行
loop.run_until_complete(asyncio.wait(tasks))
# 释放资源
loop.close()
上一页 FFmpeg

相关