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 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536
| """ Python异步编程练习题答案
运行方式: python 练习答案.py """
import asyncio import time from typing import List, Dict, Optional import random
async def countdown(seconds: int) -> None: """ 练习2.1:异步倒计时 从指定秒数倒数到0 """ for i in range(seconds, 0, -1): print(f"{i}...") await asyncio.sleep(1) print("时间到!")
async def greet_multiple_people(name_list: List[str]) -> None: """ 练习2.2:异步问候 向多个人依次问候,每次间隔1秒 """ for name in name_list: print(f"你好,{name}!") await asyncio.sleep(1)
async def download_file(filename: str, size_mb: int) -> Dict[str, any]: """ 练习2.3:模拟下载 模拟下载文件(每MB需要0.5秒) """ print(f"📥 开始下载:{filename} ({size_mb}MB)")
start_time = time.time() download_time = size_mb * 0.5 await asyncio.sleep(download_time) duration = time.time() - start_time
print(f"✅ 下载完成:{filename}")
return { "filename": filename, "size": size_mb, "duration": duration }
async def query_weather(city: str) -> Dict[str, any]: """ 练习3.1:查询单个城市的天气(模拟) """ await asyncio.sleep(random.uniform(0.3, 0.8))
return { "city": city, "温度": random.randint(15, 30), "weather": random.choice(["晴天", "多云", "小雨", "阴天"]) }
async def batch_query_weather(city_list: List[str]) -> List[Dict]: """ 练习3.1:批量查询多个城市的天气 """ print(f"🌤️ 查询 {len(city_list)} 个城市的天气...")
task_list = [query_weather(city) for city in city_list] result_list = await asyncio.gather(*task_list)
return result_list
async def throttled_downloader(file_list: List[str], max_concurrency: int = 3) -> None: """ 练习3.2:throttled_downloader 控制最多同时下载的文件数 """ semaphore = asyncio.Semaphore(max_concurrency)
async def limited_download(filename: str): async with semaphore: print(f"📥 开始下载:{filename}") await asyncio.sleep(1) print(f"✅ 完成下载:{filename}") return filename
print(f"🚀 开始下载(最多同时{max_concurrency}个)...") task_list = [throttled_download(file) for file in file_list] await asyncio.gather(*task_list) print("✅ 全部下载完成!")
async def execute_task( task_name: str, timeout_seconds: int = 5, max_retry: int = 3 ) -> Optional[str]: """ 练习3.3:执行任务,支持超时和重试 """
async def actual_task(): """模拟可能失败的任务""" await asyncio.sleep(random.uniform(0.5, 2)) if random.random() < 0.3: raise Exception("任务执行失败") return f"{任务名}completed"
for attempt_count in range(max_retry): try: print(f" 尝试 {attempt_count + 1}/{max_retry}: {任务名}")
result = await asyncio.wait_for(actual_task(), timeout=timeout_seconds)
print(f" ✅ {任务名}成功") return result
except asyncio.TimeoutError: print(f" ❌ {任务名}超时")
except Exception as e: print(f" ❌ {任务名}失败:{e}")
if attempt_count < max_retry - 1: wait_time = (attempt_count + 1) * 0.5 print(f" ⏳ 等待 {wait_time}秒 后重试...") await asyncio.sleep(wait_time)
print(f" ❌ {任务名}最终失败") return None
async def download_image(url: str, save_path: str) -> bool: """ 练习4.1:下载单张图片(模拟) """ try: print(f"📥 download_image:{url}")
await asyncio.sleep(random.uniform(0.5, 1.5))
print(f"💾 保存到:{保存路径}")
return True
except Exception as e: print(f"❌ 下载失败:{url} - {e}") return False
async def batch_download_images(image_list: List[tuple]) -> Dict[str, int]: """ 练习4.1:batch_download_images """ print(f"🚀 开始下载 {len(image_list)} 张图片...")
task_list = [download_image(url, path) for url, path in image_list] result_list = await asyncio.gather(*task_list)
success_count = sum(1 for r in result_list if r) failure_count = len(result_list) - success_count
return {"成功": success_count, "失败": failure_count}
async def check_api(url: str) -> Dict[str, any]: """ 练习4.2:检查API是否可用 """ try: start_time = time.time()
await asyncio.sleep(random.uniform(0.1, 0.5))
response_time = time.time() - start_time
available = random.random() < 0.9
return { "url": url, "available": available, "response_time": response_time }
except Exception as e: return { "url": url, "available": False, "错误": str(e) }
async def monitor_api(url_list: List[str], check_interval: int = 60, check_count: int = 3) -> None: """ 练习4.2:持续监控API(简化版,只检查3次) """ print(f"🔍 开始监控 {len(url_list)} 个API...")
for round in range(check_count): print(f"\n第 {round + 1} 轮检查:")
task_list = [check_api(url) for url in url_list] result_list = await asyncio.gather(*task_list)
for result in result_list: status = "✅" if result["available"] else "❌" if result["available"]: print(f" {status} {result['url']} - response_time: {result['response_time']:.2f}秒") else: print(f" {status} {result['url']} - 不可用")
if round < check_count - 1: print(f"\n⏳ 等待 {check_interval}秒...") await asyncio.sleep(check_interval)
async def smart_crawl( url: str, max_retry: int = 3, timeout_seconds: int = 10 ) -> Optional[str]: """ 练习4.3:智能爬取网页 带重试、超时、错误处理 """
async def crawl(): """实际爬取操作""" await asyncio.sleep(random.uniform(0.5, 2))
if random.random() < 0.8: return f"网页内容:{url}" else: raise Exception("网络错误")
for attempt_count in range(max_retry): try: print(f" 🕷️ 尝试 {attempt_count + 1}/{max_retry}: {url}")
result = await asyncio.wait_for(crawl(), timeout=timeout_seconds)
print(f" ✅ 爬取成功") return result
except asyncio.TimeoutError: print(f" ❌ 超时")
except Exception as e: print(f" ❌ 失败:{e}")
if attempt_count < max_retry - 1: wait_time = (attempt_count + 1) * 1.0 await asyncio.sleep(wait_time)
print(f" ❌ 爬取最终失败") return None
async def analyze_log(file_path: str) -> Dict[str, int]: """ 练习5.1:分析日志文件 """ await asyncio.sleep(0.2)
return { "INFO": random.randint(50, 100), "WARNING": random.randint(10, 30), "ERROR": random.randint(0, 10) }
async def batch_analyze_logs(file_list: List[str]) -> Dict[str, int]: """ 练习5.1:批量分析多个日志文件 """ print(f"📝 分析 {len(file_list)} 个日志文件...")
task_list = [analyze_log(file) for file in file_list] result_list = await asyncio.gather(*task_list)
total_stats = {"INFO": 0, "WARNING": 0, "ERROR": 0} for result in result_list: for level, count in result.items(): total_stats[level] += count
return total_stats
""" 问题1:task1 = async_function1() - 忘记使用 await,只得到协程对象
问题2:time.sleep(2) - 使用了阻塞操作,应该用 asyncio.sleep(2)
问题3:虽然使用了await,但任务1从未真正执行
正确代码: """
async def fixed_code(): result1 = await async_function1()
await asyncio.sleep(2)
return result1
""" 问题:每次循环都创建新的session,浪费资源
优化后的代码: """
async def optimized_code(): result_list = []
return result_list
""" 优化后的代码: """
async def code_with_error_handling(url: str) -> Optional[Dict]: try: pass
except asyncio.TimeoutError: print(f"❌ 请求超时:{url}") return None
except Exception as e: print(f"❌ 未知错误:{e}") return None
async def test_lesson2(): """测试第2课练习""" print("\n" + "=" * 50) print("📚 第2课练习测试") print("=" * 50)
print("\n练习2.1:异步倒计时") await countdown(3)
print("\n练习2.2:异步问候") await greet_multiple_people(["小明", "小红"])
print("\n练习2.3:模拟下载") result = await download_file("test.pdf", 4) print(f"下载结果:{result}")
async def test_lesson3(): """测试第3课练习""" print("\n" + "=" * 50) print("📚 第3课练习测试") print("=" * 50)
print("\n练习3.1:batch_query_weather") city_list = ["北京", "上海", "广州"] result = await batch_query_weather(city_list) for weather in result: print(f" {weather['city']}: {weather['温度']}°C, {weather['weather']}")
print("\n练习3.2:throttled_downloader") file_list = [f"file{i}.txt" for i in range(1, 6)] await throttled_downloader(file_list, max_concurrency=2)
print("\n练习3.3:超时重试") await execute_task("测试任务", timeout_seconds=3, max_retry=2)
async def test_lesson4(): """测试第4课练习""" print("\n" + "=" * 50) print("📚 第4课练习测试") print("=" * 50)
print("\n练习4.1:batch_download_images") image_list = [ ("https://example.com/1.jpg", "img1.jpg"), ("https://example.com/2.jpg", "img2.jpg"), ("https://example.com/3.jpg", "img3.jpg"), ] stats = await batch_download_images(image_list) print(f"下载统计:{统计}")
print("\n练习4.2:API监控") url_list = [ "https://api1.com/health", "https://api2.com/health", ] await monitor_api(url_list, check_interval=2, check_count=2)
print("\n练习4.3:smart_crawl") await smart_crawl("https://example.com", max_retry=2)
async def test_lesson5(): """测试第5课练习""" print("\n" + "=" * 50) print("📚 第5课练习测试") print("=" * 50)
print("\n练习5.1:batch_analyze_logs") file_list = ["log1.txt", "log2.txt", "log3.txt"] stats = await batch_analyze_logs(file_list) print(f"日志统计:{统计}")
async def main(): """主程序""" print("🎓 Python异步编程练习答案") print("=" * 50)
await test_lesson2() await test_lesson3() await test_lesson4() await test_lesson5()
print("\n" + "=" * 50) print("🎉 所有练习测试完成!") print("=" * 50) print(""" 💡 学习建议: 1. 对比自己的答案和参考答案 2. 理解每个解决方案的思路 3. 尝试优化和改进代码 4. 应用到实际项目中 📚 继续学习: 1. 阅读官方文档 2. 研究优秀开源项目 3. 实践更多项目 4. 分享学习心得 🚀 加油! """)
if __name__ == "__main__": asyncio.run(main())
|