{"id":735,"date":"2026-03-31T12:11:00","date_gmt":"2026-03-31T04:11:00","guid":{"rendered":"https:\/\/mitongxue.cn\/?p=735"},"modified":"2026-07-21T12:22:35","modified_gmt":"2026-07-21T04:22:35","slug":"python%e5%bc%82%e6%ad%a5%e7%bc%96%e7%a8%8b","status":"publish","type":"post","link":"https:\/\/mitongxue.cn\/index.php\/2026\/03\/31\/python%e5%bc%82%e6%ad%a5%e7%bc%96%e7%a8%8b\/","title":{"rendered":"python\u5f02\u6b65\u7f16\u7a0b"},"content":{"rendered":"\n<h2 class=\"wp-block-heading\">\u5f02\u6b65\u751f\u6210\u5668\u4e0e\u5f02\u6b65\u8fed\u4ee3\u5668<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">\u5728\u534f\u7a0b\u51fd\u6570\u4e2d\u4f7f\u7528 <code>yield<\/code>\uff0c\u5c31\u53d8\u6210\u4e86<strong>\u5f02\u6b65\u751f\u6210\u5668<\/strong>\u3002\u5b83\u6bcf\u6b21 <code>yield<\/code> \u4ea7\u51fa\u503c\u65f6\u90fd\u53ef\u4ee5 <code>await<\/code> \u5176\u4ed6\u534f\u7a0b\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>async def async_generator():<br> &nbsp; &nbsp;for i in range(3):<br> &nbsp; &nbsp; &nbsp; &nbsp;await asyncio.sleep(1)<br> &nbsp; &nbsp; &nbsp; &nbsp;yield i<br>\u200b<br>\u200b<br>async def main():<br> &nbsp; &nbsp;# \u5fc5\u987b\u7528 async for \u6765\u904d\u5386\u5f02\u6b65\u751f\u6210\u5668<br> &nbsp; &nbsp;async for item in async_generator():<br> &nbsp; &nbsp; &nbsp; &nbsp;print(item) &nbsp;# \u6bcf\u9694 1 \u79d2\u6253\u5370\u4e00\u4e2a\u6570\u5b57<br>\u200b<br>\u200b<br>asyncio.run(main())<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-preformatted\">\u540c\u6837\u53ef\u4ee5\u81ea\u5b9a\u4e49**\u5f02\u6b65\u8fed\u4ee3\u5668**\uff0c\u5b9e\u73b0 `__aiter__` \u548c `__anext__` \u4e24\u4e2a\u534f\u8bae\u65b9\u6cd5\uff1a<\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>class AsyncCounter:\n    def __init__(self, limit: int):\n        self._limit = limit\n        self._count = 0\n\n    def __aiter__(self):\n        return self\n\n    async def __anext__(self) -> int:\n        self._count += 1\n        if self._count > self._limit:\n            raise StopAsyncIteration\n        await asyncio.sleep(0.5)\n        return self._count\n\n\nasync def main():\n    async for num in AsyncCounter(5):\n        print(num)  # \u6bcf\u9694 0.5 \u79d2\u6253\u5370 1 2 3 4 5<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">\u5bf9\u6bd4\u540c\u6b65\u8fed\u4ee3\u534f\u8bae\uff1a<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th class=\"has-text-align-left\" data-align=\"left\">\u540c\u6b65<\/th><th class=\"has-text-align-left\" data-align=\"left\">\u5f02\u6b65<\/th><\/tr><\/thead><tbody><tr><td class=\"has-text-align-left\" data-align=\"left\"><code>__iter__<\/code> \/ <code>__next__<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\"><code>__aiter__<\/code> \/ <code>__anext__<\/code><\/td><\/tr><tr><td class=\"has-text-align-left\" data-align=\"left\"><code>for x in iterable<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\"><code>async for x in async_iterable<\/code><\/td><\/tr><tr><td class=\"has-text-align-left\" data-align=\"left\"><code>StopIteration<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\"><code>StopAsyncIteration<\/code><\/td><\/tr><tr><td class=\"has-text-align-left\" data-align=\"left\">\u751f\u6210\u5668 <code>yield<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\">\u5f02\u6b65\u751f\u6210\u5668 <code>async def<\/code> + <code>yield<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<p class=\"wp-block-paragraph\">\u5f02\u6b65\u4e0a\u4e0b\u6587\u7ba1\u7406\u5668<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><code>async with<\/code> \u80cc\u540e\u662f <code>__aenter__<\/code> \u548c <code>__aexit__<\/code> \u4e24\u4e2a\u534f\u8bae\u65b9\u6cd5\uff0c\u548c\u540c\u6b65\u7684 <code>with<\/code> \u7c7b\u4f3c\uff0c\u53ea\u662f\u90fd\u662f\u5f02\u6b65\u7684\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>class AsyncResource:<br> &nbsp; &nbsp;async def __aenter__(self):<br> &nbsp; &nbsp; &nbsp; &nbsp;print(\"\u83b7\u53d6\u8d44\u6e90\")<br> &nbsp; &nbsp; &nbsp; &nbsp;await asyncio.sleep(0.5)<br> &nbsp; &nbsp; &nbsp; &nbsp;return self<br>\u200b<br> &nbsp; &nbsp;async def __aexit__(self, exc_type, exc_val, exc_tb):<br> &nbsp; &nbsp; &nbsp; &nbsp;print(\"\u91ca\u653e\u8d44\u6e90\")<br> &nbsp; &nbsp; &nbsp; &nbsp;await asyncio.sleep(0.5)<br>\u200b<br>\u200b<br>async def main():<br> &nbsp; &nbsp;async with AsyncResource() as res:<br> &nbsp; &nbsp; &nbsp; &nbsp;print(\"\u4f7f\u7528\u8d44\u6e90\")<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">\u5bf9\u6bd4\u540c\u6b65\u4e0a\u4e0b\u6587\u7ba1\u7406\u5668\uff1a<\/p>\n\n\n\n<figure class=\"wp-block-table\"><table class=\"has-fixed-layout\"><thead><tr><th class=\"has-text-align-left\" data-align=\"left\">\u540c\u6b65<\/th><th class=\"has-text-align-left\" data-align=\"left\">\u5f02\u6b65<\/th><\/tr><\/thead><tbody><tr><td class=\"has-text-align-left\" data-align=\"left\"><code>__enter__<\/code> \/ <code>__exit__<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\"><code>__aenter__<\/code> \/ <code>__aexit__<\/code><\/td><\/tr><tr><td class=\"has-text-align-left\" data-align=\"left\"><code>with ctx<\/code><\/td><td class=\"has-text-align-left\" data-align=\"left\"><code>async with ctx<\/code><\/td><\/tr><\/tbody><\/table><\/figure>\n\n\n\n<h2 class=\"wp-block-heading\">\u5b98\u65b9 asyncio \u6838\u5fc3 API<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">sleep \u2014\u2014 \u975e\u963b\u585e\u7b49\u5f85<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">\u4f7f\u7528 <code>loop.call_later<\/code> + <code>Future<\/code> \u5b9e\u73b0\u7684\u5ef6\u65f6\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>def async_delay(duration: int):<br> &nbsp; &nbsp;loop = asyncio.get_event_loop()<br> &nbsp; &nbsp;future = loop.create_future()<br> &nbsp; &nbsp;loop.call_later(duration, future.set_result, None)<br> &nbsp; &nbsp;return future<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">\u5b98\u65b9\u76f4\u63a5\u63d0\u4f9b\u4e86 <code>asyncio.sleep<\/code>\uff0c\u7528\u6cd5\u5b8c\u5168\u76f8\u540c\uff1a<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>async def main():<br> &nbsp; &nbsp;print(\"\u5f00\u59cb\")<br> &nbsp; &nbsp;await asyncio.sleep(1) &nbsp;# \u6302\u8d77\u5f53\u524d\u534f\u7a0b 1 \u79d2\uff0c\u4e8b\u4ef6\u5faa\u73af\u53bb\u8c03\u5ea6\u5176\u4ed6\u534f\u7a0b<br> &nbsp; &nbsp;print(\"1\u79d2\u540e\")<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">\u521b\u5efa\u4e0e\u8fd0\u884c\u534f\u7a0b<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import asyncio<br>\u200b<br>\u200b<br>async def say_hello():<br> &nbsp; &nbsp;await asyncio.sleep(1)<br> &nbsp; &nbsp;return \"Hello\"<br>\u200b<br>\u200b<br>async def main():<br> &nbsp; &nbsp;# 1. asyncio.run \u2014\u2014 \u6700\u9ad8\u5c42\u5165\u53e3<br> &nbsp; &nbsp;pass<br>\u200b<br>result = asyncio.run(say_hello())<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">create_task \u2014\u2014 \u5c06\u534f\u7a0b\u5305\u88c5\u6210 Task \u5e76\u8c03\u5ea6\u6267\u884c<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>async def main():<br> &nbsp; &nbsp;# \u521b\u5efa Task\uff0c\u534f\u7a0b\u4f1a\u7acb\u5373\u88ab\u8c03\u5ea6\u5230\u4e8b\u4ef6\u5faa\u73af\u4e2d\u6267\u884c<br> &nbsp; &nbsp;task = asyncio.create_task(say_hello())<br> &nbsp; &nbsp;# \u8fd9\u91cc\u53ef\u4ee5\u505a\u522b\u7684\u4e8b\uff0ctask \u5df2\u7ecf\u5728\u540e\u53f0\u8fd0\u884c<br> &nbsp; &nbsp;result = await task &nbsp;# \u7b49\u5f85 task \u5b8c\u6210<br> &nbsp; &nbsp;print(result)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">gather \u2014\u2014 \u5e76\u53d1\u6267\u884c\u591a\u4e2a\u534f\u7a0b<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>async def fetch(url: str, delay: int) -&gt; str:<br> &nbsp; &nbsp;await asyncio.sleep(delay)<br> &nbsp; &nbsp;return f\"{url} \u5b8c\u6210\"<br>\u200b<br>\u200b<br>async def main():<br> &nbsp; &nbsp;# \u540c\u65f6\u53d1\u8d77\u591a\u4e2a\u8bf7\u6c42\uff0c\u7b49\u5f85\u6240\u6709\u5b8c\u6210<br> &nbsp; &nbsp;results = await asyncio.gather(<br> &nbsp; &nbsp; &nbsp; &nbsp;fetch(\"url1\", 2),<br> &nbsp; &nbsp; &nbsp; &nbsp;fetch(\"url2\", 1),<br> &nbsp; &nbsp; &nbsp; &nbsp;fetch(\"url3\", 3),<br> &nbsp;  )<br> &nbsp; &nbsp;print(results) &nbsp;# &#91;'url1 \u5b8c\u6210', 'url2 \u5b8c\u6210', 'url3 \u5b8c\u6210']<br>\u200b<br>\u200b<br>asyncio.run(main())<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\">gather \u7684\u7279\u70b9\uff1a<\/p>\n\n\n\n<ul class=\"wp-block-list\">\n<li>\u6240\u6709\u534f\u7a0b<strong>\u5e76\u53d1<\/strong>\u6267\u884c<\/li>\n\n\n\n<li>\u8fd4\u56de\u7ed3\u679c\u987a\u5e8f\u4e0e\u4f20\u5165\u987a\u5e8f\u4e00\u81f4<\/li>\n\n\n\n<li>\u4efb\u4f55\u4e00\u4e2a\u534f\u7a0b\u629b\u51fa\u5f02\u5e38\uff0cgather \u4f1a\u7acb\u5373\u4f20\u64ad\u5f02\u5e38\uff08\u5176\u4ed6\u534f\u7a0b\u4ecd\u4f1a\u7ee7\u7eed\u8fd0\u884c\uff09<\/li>\n\n\n\n<li>\u53ef\u901a\u8fc7 <code>return_exceptions=True<\/code> \u8ba9\u5f02\u5e38\u4ee5\u7ed3\u679c\u5f62\u5f0f\u8fd4\u56de\uff0c\u4e0d\u4e2d\u65ad gather<\/li>\n<\/ul>\n\n\n\n<pre class=\"wp-block-code\"><code>async def fail() -&gt; str:<br> &nbsp; &nbsp;raise ValueError(\"\u51fa\u9519\u4e86\")<br>\u200b<br>\u200b<br>async def main():<br> &nbsp; &nbsp;results = await asyncio.gather(<br> &nbsp; &nbsp; &nbsp; &nbsp;fetch(\"ok\", 1),<br> &nbsp; &nbsp; &nbsp; &nbsp;fail(),<br> &nbsp; &nbsp; &nbsp; &nbsp;return_exceptions=True, &nbsp;# \u5c06\u5f02\u5e38\u4f5c\u4e3a\u8fd4\u56de\u503c\uff0c\u4e0d\u629b\u51fa<br> &nbsp;  )<br> &nbsp; &nbsp;print(results) &nbsp;# &#91;'ok \u5b8c\u6210', ValueError('\u51fa\u9519\u4e86')]<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">wait \u2014\u2014 \u66f4\u7075\u6d3b\u7684\u7b49\u5f85\u65b9\u5f0f<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import asyncio<br>from typing import Coroutine<br>\u200b<br>\u200b<br>async def main():<br> &nbsp; &nbsp;tasks = &#91;<br> &nbsp; &nbsp; &nbsp; &nbsp;asyncio.create_task(fetch(\"A\", 2)),<br> &nbsp; &nbsp; &nbsp; &nbsp;asyncio.create_task(fetch(\"B\", 1)),<br> &nbsp; &nbsp; &nbsp; &nbsp;asyncio.create_task(fetch(\"C\", 3)),<br> &nbsp;  ]<br>\u200b<br> &nbsp; &nbsp;# FIRST_COMPLETED: \u4efb\u4e00\u5b8c\u6210\u5c31\u8fd4\u56de<br> &nbsp; &nbsp;# FIRST_EXCEPTION: \u4efb\u4e00\u5f02\u5e38\u5c31\u8fd4\u56de<br> &nbsp; &nbsp;# ALL_COMPLETED: \u5168\u90e8\u5b8c\u6210\uff08\u9ed8\u8ba4\uff09<br> &nbsp; &nbsp;done, pending = await asyncio.wait(tasks, return_when=asyncio.FIRST_COMPLETED)<br> &nbsp; &nbsp;print(f\"\u5df2\u5b8c\u6210: {len(done)}, \u5f85\u5b8c\u6210: {len(pending)}\")<br>\u200b<br> &nbsp; &nbsp;# \u8fd8\u53ef\u4ee5\u624b\u52a8\u5904\u7406\u672a\u5b8c\u6210\u7684\u4efb\u52a1<br> &nbsp; &nbsp;for task in pending:<br> &nbsp; &nbsp; &nbsp; &nbsp;task.cancel()<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">as_completed \u2014\u2014 \u8c01\u5148\u5b8c\u6210\u8c01\u5148\u5904\u7406<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>async def main():<br> &nbsp; &nbsp;coros = &#91;fetch(\"A\", 2), fetch(\"B\", 1), fetch(\"C\", 3)]<br>\u200b<br> &nbsp; &nbsp;for coro in asyncio.as_completed(coros):<br> &nbsp; &nbsp; &nbsp; &nbsp;result = await coro<br> &nbsp; &nbsp; &nbsp; &nbsp;print(result) &nbsp;# \u6309\u7167\u5b8c\u6210\u7684\u5148\u540e\u987a\u5e8f\u6253\u5370<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">TaskGroup \u2014\u2014 \u7ed3\u6784\u5316\u5e76\u53d1\uff08Python 3.11+\uff09<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>async def main():<br> &nbsp; &nbsp;# TaskGroup \u4fdd\u8bc1\u6240\u6709\u5b50\u4efb\u52a1\u5728\u9000\u51fa\u524d\u5b8c\u6210<br> &nbsp; &nbsp;# \u5982\u679c\u67d0\u4e2a\u5b50\u4efb\u52a1\u5f02\u5e38\uff0c\u4f1a\u53d6\u6d88\u7ec4\u5185\u6240\u6709\u5176\u4ed6\u4efb\u52a1<br> &nbsp; &nbsp;async with asyncio.TaskGroup() as tg:<br> &nbsp; &nbsp; &nbsp; &nbsp;task1 = tg.create_task(fetch(\"A\", 2))<br> &nbsp; &nbsp; &nbsp; &nbsp;task2 = tg.create_task(fetch(\"B\", 1))<br> &nbsp; &nbsp; &nbsp; &nbsp;task3 = tg.create_task(fetch(\"C\", 3))<br>\u200b<br> &nbsp; &nbsp;# \u5230\u8fd9\u91cc\u6240\u6709\u4efb\u52a1\u90fd\u5df2\u5b89\u5168\u5b8c\u6210<br> &nbsp; &nbsp;print(task1.result(), task2.result(), task3.result())<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Lock \u2014\u2014 \u4e92\u65a5\u9501<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">\u591a\u4e2a\u534f\u7a0b\u53ef\u80fd\u7ade\u4e89\u5171\u4eab\u8d44\u6e90\uff0cLock \u4fdd\u8bc1\u540c\u4e00\u65f6\u523b\u53ea\u6709\u4e00\u4e2a\u534f\u7a0b\u80fd\u8bbf\u95ee<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import asyncio<br>\u200b<br>shared_data: int = 0<br>lock = asyncio.Lock()<br>\u200b<br>\u200b<br>async def safe_increment():<br> &nbsp; &nbsp;global shared_data<br> &nbsp; &nbsp;async with lock: &nbsp;# \u83b7\u53d6\u9501\uff0c\u7b49\u9501\u91ca\u653e\u524d\u5176\u4ed6\u534f\u7a0b\u4f1a\u5728\u6b64\u7b49\u5f85<br> &nbsp; &nbsp; &nbsp; &nbsp;temp = shared_data<br> &nbsp; &nbsp; &nbsp; &nbsp;await asyncio.sleep(0) &nbsp;# \u6a21\u62df\u8017\u65f6\u64cd\u4f5c\uff0c\u6b64\u65f6\u5207\u6362\u534f\u7a0b\u4e5f\u4e0d\u4f1a\u51fa\u95ee\u9898<br> &nbsp; &nbsp; &nbsp; &nbsp;shared_data = temp + 1<br>\u200b<br>\u200b<br>async def main():<br> &nbsp; &nbsp;await asyncio.gather(*&#91;safe_increment() for _ in range(100)])<br> &nbsp; &nbsp;print(shared_data) &nbsp;# 100<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Event \u2014\u2014 \u4e8b\u4ef6\u901a\u77e5<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">\u4e00\u4e2a\u534f\u7a0b\u7b49\u5f85\u53e6\u4e00\u4e2a\u534f\u7a0b\u53d1\u51fa\u4fe1\u53f7<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>async def waiter(event: asyncio.Event):<br> &nbsp; &nbsp;print(\"waiter: \u5f00\u59cb\u7b49\u5f85\")<br> &nbsp; &nbsp;await event.wait() &nbsp;# \u7b49\u5f85\u4e8b\u4ef6\u88ab\u8bbe\u7f6e<br> &nbsp; &nbsp;print(\"waiter: \u88ab\u5524\u9192\")<br>\u200b<br>\u200b<br>async def setter(event: asyncio.Event):<br> &nbsp; &nbsp;print(\"setter: 1\u79d2\u540e\u8bbe\u7f6e\u4e8b\u4ef6\")<br> &nbsp; &nbsp;await asyncio.sleep(1)<br> &nbsp; &nbsp;event.set() &nbsp;# \u8bbe\u7f6e\u4e8b\u4ef6\uff0c\u5524\u9192\u6240\u6709\u7b49\u5f85\u8005<br>\u200b<br>\u200b<br>async def main():<br> &nbsp; &nbsp;event = asyncio.Event()<br> &nbsp; &nbsp;await asyncio.gather(waiter(event), setter(event))<\/code><\/pre>\n\n\n\n<pre class=\"wp-block-code\"><code>waiter: \u5f00\u59cb\u7b49\u5f85<br>setter: 1\u79d2\u540e\u8bbe\u7f6e\u4e8b\u4ef6<br>waiter: \u88ab\u5524\u9192<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Semaphore \u2014\u2014 \u9650\u5236\u5e76\u53d1\u6570<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>semaphore = asyncio.Semaphore(3) &nbsp;# \u540c\u65f6\u6700\u591a 3 \u4e2a<br>\u200b<br>\u200b<br>async def limited_fetch(url: str):<br> &nbsp; &nbsp;async with semaphore: &nbsp;# \u8d85\u8fc7\u5e76\u53d1\u9650\u5236\u65f6\u7b49\u5f85<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f\"\u5f00\u59cb\u8bf7\u6c42 {url}\")<br> &nbsp; &nbsp; &nbsp; &nbsp;await asyncio.sleep(1)<br> &nbsp; &nbsp; &nbsp; &nbsp;print(f\"\u5b8c\u6210\u8bf7\u6c42 {url}\")<br> &nbsp; &nbsp; &nbsp; &nbsp;return url<br>\u200b<br>\u200b<br>async def main():<br> &nbsp; &nbsp;urls = &#91;f\"url{i}\" for i in range(10)]<br> &nbsp; &nbsp;await asyncio.gather(*&#91;limited_fetch(url) for url in urls])<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">Queue \u2014\u2014 \u5f02\u6b65\u961f\u5217<\/h3>\n\n\n\n<p class=\"wp-block-paragraph\">\u751f\u4ea7\u8005-\u6d88\u8d39\u8005\u6a21\u5f0f\u7684\u57fa\u77f3<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import random\n\n\nasync def producer(queue: asyncio.Queue):\n    for i in range(10):\n        item = f\"item_{i}\"\n        await queue.put(item)\n        print(f\"\u751f\u4ea7: {item}\")\n        await asyncio.sleep(random.random())\n    await queue.put(None)  # \u53d1\u9001\u7ed3\u675f\u4fe1\u53f7\n\n\nasync def consumer(name: str, queue: asyncio.Queue):\n    while True:\n        item = await queue.get()\n        if item is None:  # \u6536\u5230\u7ed3\u675f\u4fe1\u53f7\n            queue.task_done()\n            break\n        print(f\"{name} \u6d88\u8d39: {item}\")\n        queue.task_done()\n\n\nasync def main():\n    queue = asyncio.Queue(maxsize=5)\n    await asyncio.gather(\n        producer(queue),\n        consumer(\"C1\", queue),\n        consumer(\"C2\", queue),\n    )<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">asyncio.wait_for<\/h2>\n\n\n\n<p class=\"wp-block-paragraph\">\u5f02\u6b65\u7f16\u7a0b\u4e2d\u7528\u4e8e<strong>\u63a7\u5236\u4efb\u52a1\u6267\u884c\u65f6\u95f4<\/strong>\u7684\u6838\u5fc3\u51fd\u6570\u3002\u5b83\u5141\u8bb8\u4f60\u7b49\u5f85\u4e00\u4e2a\u534f\u7a0b\u6216\u4efb\u52a1\uff08Task\uff09\u5b8c\u6210\uff0c\u4f46\u524d\u63d0\u662f\u5fc5\u987b\u5728\u6307\u5b9a\u7684\u8d85\u65f6\u65f6\u95f4\uff08timeout\uff09\u5185\u5b8c\u6210\u3002<\/p>\n\n\n\n<ol class=\"wp-block-list\">\n<li><strong>\u8d85\u65f6\u53d6\u6d88<\/strong>\uff1a\u5982\u679c\u5728\u8bbe\u5b9a\u7684 <code>timeout<\/code> \u79d2\u6570\u5185\uff0c\u7b49\u5f85\u7684\u5bf9\u8c61\uff08awaitable\uff09\u6ca1\u6709\u6267\u884c\u5b8c\u6bd5\uff0c<code>wait_for<\/code> \u4f1a\u4e3b\u52a8<strong>\u53d6\u6d88<\/strong>\u8be5\u4efb\u52a1\uff0c\u5e76\u629b\u51fa <code>asyncio.TimeoutError<\/code> \u5f02\u5e38\u3002<\/li>\n\n\n\n<li><strong>\u6b63\u5e38\u8fd4\u56de<\/strong>\uff1a\u5982\u679c\u4efb\u52a1\u5728\u8d85\u65f6\u524d\u987a\u5229\u5b8c\u6210\uff0c<code>wait_for<\/code> \u4f1a\u8fd4\u56de\u8be5\u4efb\u52a1\u7684\u6267\u884c\u7ed3\u679c\u3002<\/li>\n\n\n\n<li><strong>\u5f02\u5e38\u4f20\u64ad<\/strong>\uff1a\u5982\u679c\u7b49\u5f85\u7684\u4efb\u52a1\u5728\u6267\u884c\u8fc7\u7a0b\u4e2d\u629b\u51fa\u4e86\u5176\u4ed6\u672a\u5904\u7406\u7684\u5f02\u5e38\uff0c\u8be5\u5f02\u5e38\u4f1a\u76f4\u63a5\u4f20\u64ad\u7ed9\u8c03\u7528\u8005\u3002<\/li>\n<\/ol>\n\n\n\n<pre class=\"wp-block-code\"><code>async def slow_operation():\n    await asyncio.sleep(10)\n    return \"\u5b8c\u6210\"\n\n\nasync def main():\n    try:\n        result = await asyncio.wait_for(slow_operation(), timeout=2)\n    except TimeoutError:\n        print(\"\u64cd\u4f5c\u8d85\u65f6\u4e86\")<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">asyncio.timeout\uff08Python 3.11+\uff09<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>async def main():<br> &nbsp; &nbsp;try:<br> &nbsp; &nbsp; &nbsp; &nbsp;async with asyncio.timeout(2):<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;result = await slow_operation()<br> &nbsp; &nbsp;except TimeoutError:<br> &nbsp; &nbsp; &nbsp; &nbsp;print(\"\u64cd\u4f5c\u8d85\u65f6\u4e86\")<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><code>asyncio.timeout<\/code>\u00a0\u662f Python 3.11 \u5f15\u5165\u7684\u73b0\u4ee3\u8d85\u65f6\u63a7\u5236\u673a\u5236\uff0c\u4f5c\u4e3a\u4e0a\u4e0b\u6587\u7ba1\u7406\u5668\uff08Context Manager\uff09\u63d0\u4f9b\u3002\u76f8\u6bd4\u65e9\u671f\u7684\u00a0<code>asyncio.wait_for()<\/code>\uff0c\u5b83\u63d0\u4f9b\u4e86\u66f4\u4f18\u96c5\u3001\u66f4\u7075\u6d3b\u7684\u4efb\u52a1\u8d85\u65f6\u7ba1\u7406\u65b9\u5f0f\u3002<\/p>\n\n\n\n<h3 class=\"wp-block-heading\">\u5728\u5f02\u6b65\u4e2d\u8fd0\u884c\u540c\u6b65\u4ee3\u7801<\/h3>\n\n\n\n<pre class=\"wp-block-code\"><code>import time<br>\u200b<br>\u200b<br>def blocking_io() -&gt; str:<br> &nbsp; &nbsp;time.sleep(0.5) &nbsp;# \u540c\u6b65\u963b\u585e\u64cd\u4f5c<br> &nbsp; &nbsp;return \"\u6587\u4ef6\u8bfb\u53d6\u5b8c\u6210\"<br>\u200b<br>\u200b<br>def cpu_intensive() -&gt; int:<br> &nbsp; &nbsp;return sum(i * i for i in range(10_000_000))<br>\u200b<br>\u200b<br>async def main():<br> &nbsp; &nbsp;# to_thread\uff1a\u5c06\u540c\u6b65\u963b\u585e\u51fd\u6570\u653e\u5230\u7ebf\u7a0b\u6c60\u4e2d\u6267\u884c<br> &nbsp; &nbsp;result = await asyncio.to_thread(blocking_io)<br> &nbsp; &nbsp;print(result)<br>\u200b<br> &nbsp; &nbsp;# run_in_executor\uff1a\u66f4\u5e95\u5c42\uff0c\u53ef\u4ee5\u6307\u5b9a\u6267\u884c\u5668<br> &nbsp; &nbsp;loop = asyncio.get_running_loop()<br> &nbsp; &nbsp;result = await loop.run_in_executor(None, cpu_intensive)<br> &nbsp; &nbsp;print(result)<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\"><strong>1. IO \u5bc6\u96c6\u578b\u540c\u6b65\u4ee3\u7801\uff08\u5982\u7f51\u7edc\u8bf7\u6c42\u3001\u6587\u4ef6\u8bfb\u5199\uff09<\/strong><\/h3>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>\u7edd\u5bf9\u4e0d\u8981\u76f4\u63a5\u5728\u534f\u7a0b\u4e2d\u8c03\u7528<\/strong>\uff08\u4f8b\u5982\u76f4\u63a5\u4f7f\u7528&nbsp;<code>requests.get()<\/code>&nbsp;\u6216&nbsp;<code>time.sleep()<\/code>\uff09\uff0c\u8fd9\u4f1a\u963b\u585e\u5f53\u524d\u7ebf\u7a0b\u7684\u4e8b\u4ef6\u5faa\u73af\u3002<\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>\u89e3\u51b3\u65b9\u6848\uff1a\u5c06\u540c\u6b65\u51fd\u6570\u6254\u5230\u7ebf\u7a0b\u6c60\u4e2d\u6267\u884c<\/strong><\/p>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>\u73b0\u4ee3\u5199\u6cd5\uff08Python 3.9+\uff09<\/strong>\uff1a\u4f7f\u7528\u00a0<code>asyncio.to_thread()<\/code>\u3002\u5b83\u672c\u8d28\u4e0a\u662f\u00a0<code>run_in_executor<\/code>\u00a0\u7684\u7b80\u5316\u7248\uff0c\u65e0\u9700\u624b\u52a8\u83b7\u53d6\u4e8b\u4ef6\u5faa\u73af\uff0c\u4e00\u884c\u4ee3\u7801\u5373\u53ef\u5c06\u540c\u6b65\u51fd\u6570\u5305\u88c5\u4e3a\u53ef\u00a0<code>await<\/code>\u00a0\u7684\u534f\u7a0b\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>import asyncio\nimport requests\n\nasync def fetch_data():\n    # \u5c06\u540c\u6b65\u7684 requests.get \u6254\u7ed9\u9ed8\u8ba4\u7ebf\u7a0b\u6c60\u6267\u884c\n    response = await asyncio.to_thread(requests.get, 'http:\/\/example.com')\n    return response.status_code<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><strong>\u4f20\u7edf\u5199\u6cd5\uff08\u517c\u5bb9\u8001\u7248\u672c\uff09<\/strong>\uff1a\u4f7f\u7528\u00a0<code>loop.run_in_executor(None, sync_func, args)<\/code>\u3002<\/p>\n\n\n\n<pre class=\"wp-block-code\"><code>loop = asyncio.get_running_loop()\nresult = await loop.run_in_executor(None, requests.get, 'http:\/\/example.com')<\/code><\/pre>\n\n\n\n<h2 class=\"wp-block-heading\">\u7b2c\u4e09\u65b9\u5f02\u6b65\u5e93<\/h2>\n\n\n\n<h3 class=\"wp-block-heading\">\u7f51\u7edc\u8bf7\u6c42<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">aiohttp\uff08\u7b2c\u4e09\u65b9\u6700\u6d41\u884c\u7684\u5f02\u6b65 HTTP \u5e93\uff09<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>import aiohttp<br>\u200b<br>\u200b<br>async def fetch_url(url: str) -&gt; str:<br> &nbsp; &nbsp;async with aiohttp.ClientSession() as session:<br> &nbsp; &nbsp; &nbsp; &nbsp;async with session.get(url) as response:<br> &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;return await response.text()<br>\u200b<br>\u200b<br>async def main():<br> &nbsp; &nbsp;html = await fetch_url(\"https:\/\/example.com\")<br> &nbsp; &nbsp;print(len(html))<\/code><\/pre>\n\n\n\n<h4 class=\"wp-block-heading\">httpx\uff08\u652f\u6301\u540c\u6b65\/\u5f02\u6b65\u53cc\u6a21\u5f0f\uff0cAPI \u66f4\u53cb\u597d\uff09<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>import httpx<br>\u200b<br>\u200b<br>async def fetch_url(url: str) -&gt; str:<br> &nbsp; &nbsp;async with httpx.AsyncClient() as client:<br> &nbsp; &nbsp; &nbsp; &nbsp;response = await client.get(url)<br> &nbsp; &nbsp; &nbsp; &nbsp;return response.text<br>\u200b<br>\u200b<br>async def main():<br> &nbsp; &nbsp;html = await fetch_url(\"https:\/\/example.com\")<br> &nbsp; &nbsp;print(len(html))<\/code><\/pre>\n\n\n\n<h3 class=\"wp-block-heading\">\u6587\u4ef6 I\/O<\/h3>\n\n\n\n<h4 class=\"wp-block-heading\">aiofiles\uff08\u5f02\u6b65\u6587\u4ef6\u64cd\u4f5c\uff09<\/h4>\n\n\n\n<pre class=\"wp-block-code\"><code>import aiofiles<br>\u200b<br>\u200b<br>async def read_write_example():<br> &nbsp; &nbsp;# \u5199\u6587\u4ef6<br> &nbsp; &nbsp;async with aiofiles.open(\"example.txt\", \"w\") as f:<br> &nbsp; &nbsp; &nbsp; &nbsp;await f.write(\"Hello, \u5f02\u6b65\u6587\u4ef6!\\n\")<br>\u200b<br> &nbsp; &nbsp;# \u8bfb\u6587\u4ef6<br> &nbsp; &nbsp;async with aiofiles.open(\"example.txt\", \"r\") as f:<br> &nbsp; &nbsp; &nbsp; &nbsp;content = await f.read()<br> &nbsp; &nbsp; &nbsp; &nbsp;print(content)<\/code><\/pre>\n\n\n\n<p class=\"wp-block-paragraph\"><\/p>\n","protected":false},"excerpt":{"rendered":"<p>\u5f02\u6b65\u751f\u6210\u5668\u4e0e\u5f02\u6b65\u8fed\u4ee3\u5668 \u5728\u534f\u7a0b\u51fd\u6570\u4e2d\u4f7f\u7528 yiel..<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"open","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[52,14],"tags":[54],"class_list":["post-735","post","type-post","status-publish","format-standard","hentry","category-python","category-back","tag-python"],"featured_image_urls":{"full":"","thumbnail":"","medium":"","medium_large":"","large":"","1536x1536":"","2048x2048":""},"author_info":{"info":["\u9648 \u67d0\u4eba"]},"category_info":"<a href=\"https:\/\/mitongxue.cn\/index.php\/category\/back\/python\/\" rel=\"category tag\">Python<\/a> <a href=\"https:\/\/mitongxue.cn\/index.php\/category\/back\/\" rel=\"category tag\">\u540e\u7aef<\/a>","tag_info":"\u540e\u7aef","comment_count":"0","_links":{"self":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts\/735","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/comments?post=735"}],"version-history":[{"count":4,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts\/735\/revisions"}],"predecessor-version":[{"id":739,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/posts\/735\/revisions\/739"}],"wp:attachment":[{"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/media?parent=735"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/categories?post=735"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/mitongxue.cn\/index.php\/wp-json\/wp\/v2\/tags?post=735"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}