马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
本帖最后由 qiuyouzhi 于 2020-3-20 16:09 编辑
Python async 和 await
async 和 await的用法:
async 可以将一个函数包装成异步函数,
先来一段代码例子:
>>> async def hello(name = 'qiuyouzhi'):
print('Hello,', name)
>>>
>>> hello()
Warning (from warnings module):
File "C:\Users\rzzl\AppData\Local\Programs\Python\Python38\lib\idlelib\rpc.py", line 619
builtins._ = None
RuntimeWarning: coroutine 'test' was never awaited
<coroutine object hello at 0x0000018C6F5E32C0>
嗯?为什么有警告?(这里不是报错,是警告!)
这是因为async所包装的函数必须和它的好兄弟await一起,
修改一下代码:
>>> async def hello(name = 'qiuyouzhi'):
print('HELLO,', name, "!")
await test()
print("DONE!")
>>> async def test():
print("I AM TEST!")
await语句可以在异步函数中跳出去执行别的异步函数。
再测试一下:>>> print(hello().send(None))#这里如果用print(hello())调用的话只会返回这个函数的类型,所以我们可以发送一个值:
HELLO, qiuyouzhi !
I AM TEST!
DONE!
Traceback (most recent call last):
File "<pyshell#43>", line 1, in <module>
print(hello().send(None))
StopIteration
又报错了,因为协程在正常返回的时候会抛出一个
StopIteration异常,所以我们这样写:
>>> def enter(coroutine): # 异步函数会返回一个coroutine对象
try:
print(coroutine.send(None))
except StopIteration as e:
print(e.value)
>>> enter(hello())
HELLO, qiuyouzhi !
I AM TEST!
DONE!
None
补充内容 (2020-3-10 12:22):
? |