async的使用方法

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/Despairvip/article/details/79089956

async意思就是异步,用它来实现协程再好不过了

async def demo1():
    print("start1")
    print("end1")

async def demo2():
    print("start2") 
    print("1")
    print("2")
    print('end2')

c = demo1()
d = demo2()

函数执行结果

sys:1: RuntimeWarning: coroutine 'demo1' was never awaited
sys:1: RuntimeWarning: coroutine 'demo2' was never awaited

说是没有等待
async函数可以用send来运行,也可以使用await来运行

send运行结果

start1
end1
Traceback (most recent call last):
  File "/home/python/Desktop/pytest/flask3/laowang.py", line 91, in <module>
    c.send(None)
StopIteration

只能打印函数1的内容,还会报StopIteration错,使用try捕获异常

    c = demo1()
    try:
        c.send(None)
    except StopIteration:
        pass

    d = demo2()
    try:
        d.send(None)
    except StopIteration:
        pass

        print(c)
        print(d)

这样就可以执行两个函数

start1
end1
start2
a
b
end2
<coroutine object demo1 at 0x7f1b19296ba0>
<coroutine object demo2 at 0x7f1b19296d00>

但是他的运行结果还是从上到下来运行,达不到交替运行的目的

这时候就可以使用swait了,在函数中见加上swait,后面跟上要执行的函数

async def demo1():

    print("C1 start")
    await demo2()
    print("C1 end")

则会时候就起到了交替执行的效果,await和yield效果差不多,让当前函数等待,执行他后面的传入的函数

C1 start
start2
a
b
end2

猜你喜欢

转载自blog.csdn.net/Despairvip/article/details/79089956