python asyncio 代码片段

包含库文件

import asyncio

运行协程主函数

async def mn():
    print('hello')
    await asyncio.sleep(1)
    print('world')
await main()#在jupyter里的运行main函数的方法
asyncio.run(main())#在其他位置运行main函数的方法

激活调试模式

asyncio.run(main(), debug=True)

异步运行协程

async def say_after(delay, what):#定义协程要运行的函数
    await asyncio.sleep(delay)
    print(what)
async def main():#定义协程主函数
    task1 = asyncio.create_task(
        say_after(1, 'hello'))#运行协程一
    task2 = asyncio.create_task(
        say_after(2, 'world'))#运行协程二
    await task1 #等待协程一
    await task2 #等待协程二
await main()#在jupyter里的运行main函数的方法    
asyncio.run(main())#在其他位置运行main函数的方法

并发运行任务

async def factorial(name, number):#定义要并发运行的函数
    f = 1
    for i in range(2, number + 1):
        print(f"Task {name}: Compute factorial({i})...")
        await asyncio.sleep(1)
        f *= i
    print(f"Task {name}: factorial({number}) = {f}")

async def main():#定义主函数
    # Schedule three calls *concurrently*:
    await asyncio.gather(#并发运行
        factorial("A", 2),
        factorial("B", 3),
        factorial("C", 4),
    )

asyncio.run(main())

屏蔽取消操作

res = await shield(something())

等待超时

async def eternity():
    # Sleep for one hour
    await asyncio.sleep(3600)
    print('yay!')

async def main():
    # Wait for at most 1 second
    try:
        await asyncio.wait_for(eternity(), timeout=1.0)
    except asyncio.TimeoutError:
        print('timeout!')

在线程中运行

def blocking_io():
    print(f"start blocking_io at {time.strftime('%X')}")
    # Note that time.sleep() can be replaced with any blocking
    # IO-bound operation, such as file operations.
    time.sleep(1)
    print(f"blocking_io complete at {time.strftime('%X')}")

async def main():
    print(f"started main at {time.strftime('%X')}")

    await asyncio.gather(
        asyncio.to_thread(blocking_io),
        asyncio.sleep(1))

    print(f"finished main at {time.strftime('%X')}")


asyncio.run(main())

来自其他线程的日程安排

# Create a coroutine
coro = asyncio.sleep(1, result=3)

# Submit the coroutine to a given loop
future = asyncio.run_coroutine_threadsafe(coro, loop)

# Wait for the result with an optional timeout argument
assert future.result(timeout) == 3
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值