1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314
| """ 第2课示例代码:async/await 基础语法
运行方式: python 02_examples.py """
import asyncio import time from typing import List
async def simple_greeting(name: str) -> str: """最简单的异步函数""" print(f"你好,{name}!") await asyncio.sleep(1) print(f"很高兴见到你,{name}!") return f"问候完成:{name}"
async def example1_basic_syntax() -> None: """示例1:演示基础的 async/await 语法""" print("\n" + "=" * 50) print("📚 示例1:最简单的异步函数") print("=" * 50)
result = await simple_greeting("小明") print(f"返回值:{result}")
print("\n💡 关键点:") print(" 1. 用 async def 定义异步函数") print(" 2. 用 await 等待异步操作") print(" 3. await 只能在 async 函数内使用")
async def demonstrate_pause_resume() -> None: """展示协程如何暂停和恢复""" print("\n" + "=" * 50) print("📚 示例2:协程的暂停和恢复") print("=" * 50)
print("▶️ 步骤1:开始执行")
print("⏸️ 暂停1秒(这时可以执行其他任务)...") await asyncio.sleep(1)
print("▶️ 步骤2:恢复执行")
print("⏸️ 暂停1秒(这时可以执行其他任务)...") await asyncio.sleep(1)
print("▶️ 步骤3:继续执行")
print("⏸️ 暂停1秒(这时可以执行其他任务)...") await asyncio.sleep(1)
print("✅ 步骤4:completed!")
print("\n💡 关键点:") print(" 协程在每个 await 处暂停,等待完成后恢复") print(" 暂停期间,程序可以去执行其他协程")
async def boil_water() -> str: """烧水""" print("🔥 开始烧水...") await asyncio.sleep(3) print("💧 水烧开了!") return "开水"
async def brew_tea(water: str) -> str: """泡茶""" print(f"🍵 用{water}泡茶...") await asyncio.sleep(2) print("☕ 茶泡好了!") return "一杯茶"
async def example3_function_collaboration() -> None: """示例3:多个异步函数协作""" print("\n" + "=" * 50) print("📚 示例3:多个异步函数协作") print("=" * 50)
start_time = time.time()
water = await boil_water() tea = await brew_tea(water)
total_time = time.time() - start_time
print(f"\n✅ completed!得到:{tea}") print(f"⏱️ total_time:{total_time:.1f}秒")
print("\n💡 关键点:") print(" 使用 await 可以在异步函数之间传递数据") print(" 这里是顺序执行:先烧水,再泡茶")
async def make_coffee(order_id: int, coffee_type: str, brew_time: int) -> str: """制作一杯咖啡""" print(f"☕ 订单{order_id}:开始制作{coffee_type}...")
for progress in range(1, 4): await asyncio.sleep(brew_time / 3) print(f" 订单{order_id}:制作进度 {progress}/3")
print(f"✅ 订单{order_id}:{coffee_type}制作完成!") return f"{coffee_type}(订单{order_id})"
async def coffee_shop_sequential() -> None: """咖啡店营业 - 顺序处理订单(同步方式)""" print("\n" + "=" * 50) print("📚 示例4A:咖啡店 - 顺序处理订单") print("=" * 50)
start_time = time.time()
order_list = [ (1, "美式咖啡", 3), (2, "拿铁", 4), (3, "卡布奇诺", 5), ]
completed_coffees = []
for order_id, coffee_type, brew_time in order_list: coffee = await make_coffee(order_id, coffee_type, brew_time) completed_coffees.append(coffee)
total_time = time.time() - start_time
print(f"\n🎉 完成订单:{len(completed_coffees)}杯") for coffee in completed_coffees: print(f" - {coffee}") print(f"⏱️ total_time:{total_time:.1f}秒")
print("\n💭 分析:顺序处理,效率较低...")
async def coffee_shop_concurrent() -> None: """咖啡店营业 - 并发处理订单(异步方式)""" print("\n" + "=" * 50) print("📚 示例4B:咖啡店 - 并发处理订单") print("=" * 50)
start_time = time.time()
order_list = [ (1, "美式咖啡", 3), (2, "拿铁", 4), (3, "卡布奇诺", 5), ]
task_list = [make_coffee(order_id, coffee_type, brew_time) for order_id, coffee_type, brew_time in order_list]
completed_coffees = await asyncio.gather(*task_list)
total_time = time.time() - start_time
print(f"\n🎉 完成订单:{len(completed_coffees)}杯") for coffee in completed_coffees: print(f" - {coffee}") print(f"⏱️ total_time:{total_time:.1f}秒")
print("\n💭 分析:并发处理,效率大大提高!")
async def example5_common_errors() -> None: """示例5:演示常见错误和正确做法""" print("\n" + "=" * 50) print("📚 示例5:常见错误和正确做法") print("=" * 50)
print("\n❌ 错误1:忘记使用 await") print("代码:result = simple_greeting('小红')") result_error = simple_greeting("小红") print(f"result:{result_error}") print("说明:这样只会得到协程对象,不会真正执行!")
print("\n✅ 正确做法:使用 await") print("代码:result = await simple_greeting('小红')") result_correct = await simple_greeting("小红") print(f"result:{result_correct}") print("说明:使用 await 才会真正执行!")
print("\n💡 记住:") print(" 调用异步函数时,一定要用 await") print(" 否则只会得到协程对象,不会执行")
async def async_countdown(seconds: int) -> None: """异步倒计时""" print(f"\n⏰ countdown {seconds} 秒...") for i in range(seconds, 0, -1): print(f" {i}...") await asyncio.sleep(1) print(" 🎉 时间到!")
async def async_progress_bar(task_name: str, total_steps: int, step_duration: float) -> None: """异步进度条""" print(f"\n📊 {task_name}") for step in range(1, total_steps + 1): progress_percentage = (step / total_steps) * 100 progress_bar = "█" * step + "░" * (total_steps - step) print(f" [{progress_bar}] {progress_percentage:.0f}%", end="\r") await asyncio.sleep(step_duration) print(f" [{'█' * total_steps}] 100% ✅")
async def example6_utility_tools() -> None: """示例6:实用的异步工具函数""" print("\n" + "=" * 50) print("📚 示例6:实用的异步工具函数") print("=" * 50)
await asyncio.gather( async_countdown(5), async_progress_bar("download_file", 10, 0.5) )
print("\n💡 关键点:") print(" 可以创建各种实用的异步工具函数") print(" 用 asyncio.gather 可以同时运行多个")
async def main() -> None: """主程序:运行所有示例""" print("🎓 第2课:async/await 基础语法") print("=" * 50)
await example1_basic_syntax() await demonstrate_pause_resume() await example3_function_collaboration() await coffee_shop_sequential() await coffee_shop_concurrent() await example5_common_errors() await example6_utility_tools()
print("\n" + "=" * 50) print("🎉 第2课完成!") print("=" * 50) print(""" 📚 你学到了什么? 1. async def - 定义异步函数 2. await - 等待异步操作(可以暂停) 3. asyncio.run() - 运行异步程序 4. asyncio.gather() - 同时运行多个任务 5. 协程可以暂停和恢复 🎯 核心语法: async def function_name(): # 定义异步函数 result = await 异步操作() # 等待异步操作 return result asyncio.run(函数名()) # 运行异步函数 💪 动手练习: 1. 修改咖啡制作时间,观察效果 2. 增加更多咖啡订单 3. 创建自己的异步函数 4. 完成课后练习题 🎯 下一步: 学习更多并发控制技巧(第3课) """)
if __name__ == "__main__": asyncio.run(main())
|