Skip to Content
Python语言及其应用(第2版)
book

Python语言及其应用(第2版)

by Bill Lubanovic
March 2022
Intermediate to advanced
522 pages
13h 52m
Chinese
Posts & Telecom Press
Content preview from Python语言及其应用(第2版)
截然不同的
async
439
... await task_1
... await task_2
...
>>> asyncio.run(wicked())
Surrender,
Dorothy!
运行后,你会发现输出的两行文本之间没有任何延迟。这是因为它们是不同的任务。
task_1
在打印出
Surrender
之后会暂停两秒,但并不会影响到
task_2
await
类似于生成器中的
yield
,但并不会返回值,而是标记出事件循环在需要时可以暂停
的位置。
更多信息可以参见相关文档。同步代码和异步代码可以在同一个程序中共存。只要记住在
调用异步函数之前需将
async
放在
def
await
之前。
以下是一些参考。
asyncio
相关链接列表。
文章“
A
Web Crawler With asyncio Coroutines
”。
C.2
asyncio
替代
尽管
asyncio
是一个标准的
Python
包,但你也可以在没有它的情况下使用
async
await
协程和事件循环是独立的。
asyncio
的设计也有批评之声,因而出现了一些第三方替代方案。
curio
trio
下面来展示
trio
asks
(一个异步
Web
框架,以
requests
API
为模型)的一个真实用例。
C-1
显示了使用
trio
asks
实现的并发网络爬取示例,改编自
Stack Overflow
。运行
前,先安装好
trio
(使用
pip install trio
命令安装)和
asks
(使用
pip install asks
命令安装)。
C-1 ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

Python编程入门与实战

Python编程入门与实战

Posts & Telecom Press, Fabrizio Romano
Python实用技能学习指南

Python实用技能学习指南

Posts & Telecom Press, Robert Smallshire, Austin Bingham
Python技术基础视频教程

Python技术基础视频教程

保罗·J·戴特尔
Python面向对象编程指南

Python面向对象编程指南

Posts & Telecom Press, Steven F. Lott

Publisher Resources

ISBN: 9787115586223