{"id":294,"date":"2026-10-24T10:29:36","date_gmt":"2026-10-24T02:29:36","guid":{"rendered":"https:\/\/yykcj.com\/?p=294"},"modified":"2026-10-24T10:29:36","modified_gmt":"2026-10-24T02:29:36","slug":"python-%e5%bc%82%e6%ad%a5%e7%bc%96%e7%a8%8b%ef%bc%9aasyncio-%e6%b7%b1%e5%85%a5%e7%90%86%e8%a7%a3%e4%b8%8e%e5%ae%9e%e6%88%98%e6%8c%87%e5%8d%97","status":"publish","type":"post","link":"https:\/\/yykcj.com\/?p=294","title":{"rendered":"Python \u5f02\u6b65\u7f16\u7a0b\uff1aasyncio \u6df1\u5165\u7406\u89e3\u4e0e\u5b9e\u6218\u6307\u5357"},"content":{"rendered":"<h2>\u4e3a\u4ec0\u4e48\u9700\u8981 asyncio\uff1f<\/h2>\n<p>\u5728 I\/O \u5bc6\u96c6\u578b\u5e94\u7528\u4e2d\uff0c\u540c\u6b65\u963b\u585e\u6a21\u578b\u4f1a\u5bfc\u81f4\u5927\u91cf\u65f6\u95f4\u6d6a\u8d39\u5728\u7b49\u5f85\u7f51\u7edc\u54cd\u5e94\u3001\u78c1\u76d8\u8bfb\u5199\u4e0a\u3002Python \u7684 <code>asyncio<\/code> \u63d0\u4f9b\u4e86\u4e00\u79cd\u57fa\u4e8e\u4e8b\u4ef6\u5faa\u73af\u7684\u5e76\u53d1\u6a21\u578b\uff0c\u5141\u8bb8\u5355\u7ebf\u7a0b\u5185\u5e76\u53d1\u6267\u884c\u591a\u4e2a\u4efb\u52a1\uff0c\u7279\u522b\u9002\u5408\u9ad8\u5e76\u53d1\u7684\u7f51\u7edc\u670d\u52a1\u3001\u722c\u866b\u548c\u5fae\u670d\u52a1\u3002<\/p>\n<p>\u4f46\u5f88\u591a\u5f00\u53d1\u8005\u5bf9 asyncio \u7684\u7406\u89e3\u505c\u7559\u5728 <code>async\/await<\/code> \u8bed\u6cd5\u5c42\u9762\uff0c\u9047\u5230\u6027\u80fd\u95ee\u9898\u6216\u8be1\u5f02 bug \u65f6\u65e0\u4ece\u4e0b\u624b\u3002\u672c\u6587\u5c06\u4ece\u4e8b\u4ef6\u5faa\u73af\u5e95\u5c42\u51fa\u53d1\uff0c\u7ed3\u5408\u5b9e\u6218\u4ee3\u7801\uff0c\u5e26\u4f60\u771f\u6b63\u638c\u63e1 asyncio\u3002<\/p>\n<h2>\u73af\u5883\u51c6\u5907<\/h2>\n<p>\u786e\u4fdd Python \u7248\u672c \u2265 3.8\uff08\u63a8\u8350 3.10+\uff09\uff0c\u5e76\u5b89\u88c5 <code>aiohttp<\/code> \u7528\u4e8e\u7f51\u7edc\u8bf7\u6c42\u793a\u4f8b\uff1a<\/p>\n<pre><code class=\"language-bash\">\npip install aiohttp\n<\/code><\/pre>\n<h2>\u7b2c\u4e00\u6b65\uff1a\u7406\u89e3\u534f\u7a0b\u4e0e\u4e8b\u4ef6\u5faa\u73af<\/h2>\n<h3>1.1 \u534f\u7a0b\u7684\u672c\u8d28<\/h3>\n<p>\u534f\u7a0b\uff08coroutine\uff09\u662f\u53ef\u4ee5\u901a\u8fc7 <code>async def<\/code> \u5b9a\u4e49\u7684\u51fd\u6570\uff0c\u8c03\u7528\u65f6\u4e0d\u4f1a\u7acb\u5373\u6267\u884c\uff0c\u800c\u662f\u8fd4\u56de\u4e00\u4e2a\u534f\u7a0b\u5bf9\u8c61\u3002\u5b83\u9700\u8981\u88ab\u4e8b\u4ef6\u5faa\u73af\u8c03\u5ea6\u624d\u4f1a\u8fd0\u884c\u3002<\/p>\n<pre><code class=\"language-python\">\nimport asyncio\n\nasync def hello():\n    print(&quot;Hello&quot;)\n    await asyncio.sleep(1)\n    print(&quot;World&quot;)\n\n# \u76f4\u63a5\u8c03\u7528\u4e0d\u4f1a\u6267\u884c\ncoro = hello()\nprint(type(coro))  # &lt;class &#x27;coroutine&#x27;&gt;\n\n# \u901a\u8fc7\u4e8b\u4ef6\u5faa\u73af\u8fd0\u884c\nasyncio.run(hello())\n<\/code><\/pre>\n<p><code>asyncio.run()<\/code> \u662f Python 3.7+ \u63a8\u8350\u7684\u5165\u53e3\uff0c\u5b83\u81ea\u52a8\u521b\u5efa\u4e8b\u4ef6\u5faa\u73af\u3001\u8fd0\u884c\u534f\u7a0b\u5e76\u6e05\u7406\u8d44\u6e90\u3002<\/p>\n<h3>1.2 \u4e8b\u4ef6\u5faa\u73af\u7684\u5de5\u4f5c\u539f\u7406<\/h3>\n<p>\u4e8b\u4ef6\u5faa\u73af\u662f asyncio \u7684\u6838\u5fc3\uff0c\u5b83\u7ef4\u62a4\u4e00\u4e2a\u4efb\u52a1\u961f\u5217\uff0c\u4e0d\u65ad\u8f6e\u8be2 I\/O \u4e8b\u4ef6\u548c\u5b9a\u65f6\u5668\uff0c\u5f53\u67d0\u4e2a\u4efb\u52a1\u5c31\u7eea\u65f6\u6062\u590d\u5176\u6267\u884c\u3002\u4f60\u53ef\u4ee5\u628a\u5b83\u60f3\u8c61\u6210\u4e00\u4e2a\u8c03\u5ea6\u5668\uff0c\u5728\u5355\u7ebf\u7a0b\u5185\u5b9e\u73b0\u534f\u4f5c\u5f0f\u591a\u4efb\u52a1\u3002<\/p>\n<pre><code class=\"language-python\">\nimport asyncio\n\nasync def task(name, delay):\n    print(f&quot;Task {name} started&quot;)\n    await asyncio.sleep(delay)\n    print(f&quot;Task {name} finished&quot;)\n\nasync def main():\n    # \u5e76\u53d1\u8fd0\u884c\u4e24\u4e2a\u4efb\u52a1\n    await asyncio.gather(\n        task(&quot;A&quot;, 2),\n        task(&quot;B&quot;, 1)\n    )\n\nasyncio.run(main())\n<\/code><\/pre>\n<p>\u8f93\u51fa\u987a\u5e8f\uff1aTask A started \u2192 Task B started \u2192 Task B finished \u2192 Task A finished\u3002\u8fd9\u8bc1\u660e\u4e24\u4e2a\u4efb\u52a1\u5728\u7b49\u5f85\u65f6\u4ea4\u66ff\u6267\u884c\u3002<\/p>\n<h2>\u7b2c\u4e8c\u6b65\uff1a\u4efb\u52a1\u3001Future \u4e0e\u5e76\u53d1\u63a7\u5236<\/h2>\n<h3>2.1 Task\uff1a\u534f\u7a0b\u7684\u8c03\u5ea6\u5355\u5143<\/h3>\n<p><code>asyncio.create_task()<\/code> \u5c06\u534f\u7a0b\u5305\u88c5\u4e3a Task\uff0c\u7acb\u5373\u52a0\u5165\u4e8b\u4ef6\u5faa\u73af\u8c03\u5ea6\u3002\u4e0e <code>await<\/code> \u76f4\u63a5\u8c03\u7528\u4e0d\u540c\uff0cTask \u662f\u5e76\u53d1\u6267\u884c\u7684\u3002<\/p>\n<pre><code class=\"language-python\">\nasync def main():\n    task1 = asyncio.create_task(task(&quot;A&quot;, 2))\n    task2 = asyncio.create_task(task(&quot;B&quot;, 1))\n    \n    # \u7b49\u5f85\u6240\u6709\u4efb\u52a1\u5b8c\u6210\n    await task1\n    await task2\n<\/code><\/pre>\n<h3>2.2 Future\uff1a\u4f4e\u5c42\u7ea7\u7684\u5360\u4f4d\u5bf9\u8c61<\/h3>\n<p>Future \u8868\u793a\u4e00\u4e2a\u5f02\u6b65\u64cd\u4f5c\u7684\u6700\u7ec8\u7ed3\u679c\uff0c\u901a\u5e38\u7531\u5e95\u5c42\u56de\u8c03\u8bbe\u7f6e\u3002\u65e5\u5e38\u5f00\u53d1\u4e2d\u8f83\u5c11\u76f4\u63a5\u4f7f\u7528\uff0c\u4f46\u7406\u89e3\u5b83\u6709\u52a9\u4e8e\u9605\u8bfb\u5e93\u6e90\u7801\u3002<\/p>\n<pre><code class=\"language-python\">\nasync def set_future(fut):\n    await asyncio.sleep(1)\n    fut.set_result(&quot;done&quot;)\n\nasync def main():\n    loop = asyncio.get_running_loop()\n    fut = loop.create_future()\n    asyncio.create_task(set_future(fut))\n    result = await fut\n    print(result)  # done\n<\/code><\/pre>\n<h3>2.3 \u5e76\u53d1\u9650\u5236\uff1aSemaphore<\/h3>\n<p>\u65e0\u9650\u5236\u5730\u521b\u5efa\u4efb\u52a1\u53ef\u80fd\u5bfc\u81f4\u8d44\u6e90\u8017\u5c3d\u3002\u4f7f\u7528 <code>asyncio.Semaphore<\/code> \u63a7\u5236\u5e76\u53d1\u6570\uff1a<\/p>\n<pre><code class=\"language-python\">\nimport asyncio\nimport aiohttp\n\nasync def fetch(url, session, sem):\n    async with sem:\n        async with session.get(url) as response:\n            return await response.text()\n\nasync def main():\n    urls = [f&quot;https:\/\/httpbin.org\/delay\/1?i={i}&quot; for i in range(10)]\n    sem = asyncio.Semaphore(3)  # \u6700\u5927\u5e76\u53d1 3\n    async with aiohttp.ClientSession() as session:\n        tasks = [fetch(url, session, sem) for url in urls]\n        results = await asyncio.gather(*tasks)\n        print(f&quot;Fetched {len(results)} pages&quot;)\n\nasyncio.run(main())\n<\/code><\/pre>\n<h2>\u7b2c\u4e09\u6b65\uff1a\u5b9e\u6218\u2014\u2014\u5f02\u6b65\u722c\u866b\u4e0e\u8d85\u65f6\u63a7\u5236<\/h2>\n<h3>3.1 \u5e26\u8d85\u65f6\u7684\u8bf7\u6c42<\/h3>\n<p>\u7f51\u7edc\u8bf7\u6c42\u5fc5\u987b\u8bbe\u7f6e\u8d85\u65f6\uff0c\u907f\u514d\u4efb\u52a1\u6c38\u4e45\u6302\u8d77\u3002<code>asyncio.wait_for<\/code> \u53ef\u4ee5\u5305\u88c5\u4efb\u610f\u534f\u7a0b\uff1a<\/p>\n<pre><code class=\"language-python\">\nasync def fetch_with_timeout(url, session, timeout=5):\n    try:\n        async with session.get(url, timeout=timeout) as response:\n            return await response.text()\n    except asyncio.TimeoutError:\n        print(f&quot;Timeout: {url}&quot;)\n        return None\n\nasync def main():\n    async with aiohttp.ClientSession() as session:\n        result = await fetch_with_timeout(&quot;https:\/\/httpbin.org\/delay\/10&quot;, session, timeout=3)\n        print(result is None)  # True\n<\/code><\/pre>\n<h3>3.2 \u4efb\u52a1\u53d6\u6d88\u4e0e\u6e05\u7406<\/h3>\n<p>\u5f53\u67d0\u4e2a\u4efb\u52a1\u5931\u8d25\u6216\u8d85\u65f6\u65f6\uff0c\u53ca\u65f6\u53d6\u6d88\u5176\u4ed6\u4efb\u52a1\u53ef\u4ee5\u91ca\u653e\u8d44\u6e90\uff1a<\/p>\n<pre><code class=\"language-python\">\nasync def worker(name):\n    try:\n        await asyncio.sleep(10)\n    except asyncio.CancelledError:\n        print(f&quot;Worker {name} cancelled&quot;)\n        raise\n\nasync def main():\n    tasks = [asyncio.create_task(worker(i)) for i in range(3)]\n    await asyncio.sleep(1)\n    for t in tasks:\n        t.cancel()\n    await asyncio.gather(*tasks, return_exceptions=True)\n\nasyncio.run(main())\n<\/code><\/pre>\n<h2>\u7b2c\u56db\u6b65\uff1a\u5e38\u89c1\u9677\u9631\u4e0e\u6700\u4f73\u5b9e\u8df5<\/h2>\n<h3>\ud83d\udca1 \u9677\u96311\uff1a\u5728\u534f\u7a0b\u4e2d\u8c03\u7528\u963b\u585e\u51fd\u6570<\/h3>\n<p>\u540c\u6b65\u963b\u585e\u51fd\u6570\uff08\u5982 <code>time.sleep<\/code>\u3001<code>requests.get<\/code>\uff09\u4f1a\u963b\u585e\u6574\u4e2a\u4e8b\u4ef6\u5faa\u73af\uff0c\u5bfc\u81f4\u6240\u6709\u4efb\u52a1\u5361\u4f4f\u3002\u52a1\u5fc5\u4f7f\u7528\u5f02\u6b65\u66ff\u4ee3\u54c1\uff0c\u6216\u901a\u8fc7 <code>loop.run<em>in<\/em>executor<\/code> \u653e\u5230\u7ebf\u7a0b\u6c60\u6267\u884c\u3002<\/p>\n<pre><code class=\"language-python\">\nimport time\nimport asyncio\nfrom concurrent.futures import ThreadPoolExecutor\n\ndef blocking_io():\n    time.sleep(2)\n    return &quot;done&quot;\n\nasync def main():\n    loop = asyncio.get_running_loop()\n    with ThreadPoolExecutor() as pool:\n        result = await loop.run_in_executor(pool, blocking_io)\n        print(result)\n<\/code><\/pre>\n<h3>\ud83d\udca1 \u9677\u96312\uff1a\u5fd8\u8bb0 await<\/h3>\n<p>\u8c03\u7528\u534f\u7a0b\u51fd\u6570\u4f46\u5fd8\u8bb0 <code>await<\/code> \u4f1a\u5bfc\u81f4\u534f\u7a0b\u4ece\u672a\u6267\u884c\uff0c\u4e14\u4e0d\u4f1a\u62a5\u9519\uff08\u9664\u975e\u542f\u7528\u8b66\u544a\uff09\u3002\u5f00\u542f <code>asyncio<\/code> \u8c03\u8bd5\u6a21\u5f0f\u53ef\u68c0\u6d4b\uff1a<\/p>\n<pre><code class=\"language-python\">\nimport asyncio\nimport warnings\n\nasync def foo():\n    pass\n\nasync def main():\n    foo()  # \u5fd8\u8bb0 await\n\n# \u542f\u7528\u8c03\u8bd5\u6a21\u5f0f\nasyncio.run(main(), debug=True)\n<\/code><\/pre>\n<p>\u4f1a\u8f93\u51fa\u8b66\u544a\uff1a<code>coroutine 'foo' was never awaited<\/code>\u3002<\/p>\n<h3>\ud83d\udca1 \u9677\u96313\uff1a\u5f02\u5e38\u5904\u7406<\/h3>\n<p><code>asyncio.gather<\/code> \u9ed8\u8ba4\u9047\u5230\u7b2c\u4e00\u4e2a\u5f02\u5e38\u5c31\u629b\u51fa\uff0c\u5176\u4ed6\u4efb\u52a1\u7ee7\u7eed\u8fd0\u884c\u4f46\u7ed3\u679c\u88ab\u4e22\u5f03\u3002\u4f7f\u7528 <code>return_exceptions=True<\/code> \u6536\u96c6\u6240\u6709\u7ed3\u679c\uff1a<\/p>\n<pre><code class=\"language-python\">\nasync def fail():\n    raise ValueError(&quot;oops&quot;)\n\nasync def main():\n    results = await asyncio.gather(fail(), asyncio.sleep(1, result=&quot;ok&quot;), return_exceptions=True)\n    print(results)  # [ValueError(&#x27;oops&#x27;), &#x27;ok&#x27;]\n<\/code><\/pre>\n<h3>\u6700\u4f73\u5b9e\u8df5\u6e05\u5355<\/h3>\n<ul>\n<li>\u4f7f\u7528 <code>asyncio.run()<\/code> \u4f5c\u4e3a\u7a0b\u5e8f\u5165\u53e3\uff0c\u907f\u514d\u624b\u52a8\u7ba1\u7406\u4e8b\u4ef6\u5faa\u73af\u3002<\/li>\n<li>\u4e3a\u6240\u6709\u7f51\u7edc\u8bf7\u6c42\u8bbe\u7f6e\u8d85\u65f6\uff08<code>aiohttp.ClientTimeout<\/code>\uff09\u3002<\/li>\n<li>\u4f7f\u7528 <code>asyncio.Semaphore<\/code> \u9650\u5236\u5e76\u53d1\uff0c\u9632\u6b62\u8d44\u6e90\u8017\u5c3d\u3002<\/li>\n<li>\u5728\u534f\u7a0b\u4e2d\u907f\u514d\u4efb\u4f55\u540c\u6b65\u963b\u585e\u8c03\u7528\uff0c\u5fc5\u8981\u65f6\u4f7f\u7528 <code>run<em>in<\/em>executor<\/code>\u3002<\/li>\n<li>\u4f7f\u7528 <code>asyncio.create_task()<\/code> \u65f6\u4fdd\u7559\u5f15\u7528\uff0c\u9632\u6b62\u4efb\u52a1\u88ab\u5783\u573e\u56de\u6536\u3002<\/li>\n<\/ul>\n<h2>\u603b\u7ed3<\/h2>\n<p>asyncio \u7684\u5f3a\u5927\u6e90\u4e8e\u4e8b\u4ef6\u5faa\u73af\u7684\u534f\u4f5c\u5f0f\u8c03\u5ea6\uff0c\u4f46\u6b63\u786e\u4f7f\u7528\u9700\u8981\u7406\u89e3\u534f\u7a0b\u3001\u4efb\u52a1\u548c Future \u7684\u5173\u7cfb\u3002\u901a\u8fc7\u672c\u6587\u7684\u793a\u4f8b\uff0c\u4f60\u5e94\u8be5\u638c\u63e1\u4e86\u5e76\u53d1\u63a7\u5236\u3001\u8d85\u65f6\u5904\u7406\u548c\u5f02\u5e38\u7ba1\u7406\u7684\u5173\u952e\u6280\u5de7\u3002\u4e0b\u4e00\u6b65\u53ef\u4ee5\u63a2\u7d22 <code>asyncio.Queue<\/code> \u5b9e\u73b0\u751f\u4ea7\u8005-\u6d88\u8d39\u8005\u6a21\u5f0f\uff0c\u6216\u7ed3\u5408 <code>uvloop<\/code> \u63d0\u5347\u6027\u80fd\u3002<\/p>\n<p><strong>\u5ef6\u4f38\u9605\u8bfb<\/strong>\uff1a<\/p>\n<ul>\n<li>\u5b98\u65b9\u6587\u6863 <a href=\"https:\/\/docs.python.org\/3\/library\/asyncio.html\">asyncio \u2014 Asynchronous I\/O<\/a><\/li>\n<li><code>uvloop<\/code>\uff1a\u57fa\u4e8e libuv \u7684\u9ad8\u6027\u80fd\u4e8b\u4ef6\u5faa\u73af<\/li>\n<li><code>anyio<\/code>\uff1a\u517c\u5bb9 asyncio \u548c trio \u7684\u5f02\u6b65\u62bd\u8c61\u5c42<\/li>\n<\/ul>\n","protected":false},"excerpt":{"rendered":"<p>\u672c\u6587\u6df1\u5165\u89e3\u6790 Python asyncio \u7684\u6838\u5fc3\u673a\u5236\uff0c\u901a\u8fc7\u53ef\u8fd0\u884c\u7684\u4ee3\u7801\u793a\u4f8b\u6f14\u793a\u534f\u7a0b\u3001\u4efb\u52a1\u3001\u4e8b\u4ef6\u5faa\u73af\u7684\u9ad8\u7ea7\u7528\u6cd5\uff0c\u5e76\u5206\u4eab\u6027\u80fd\u4f18\u5316\u4e0e\u5e38\u89c1\u9677\u9631\u7684\u6700\u4f73\u5b9e\u8df5\uff0c\u52a9\u4f60\u6784\u5efa\u9ad8\u6548\u5f02\u6b65\u5e94\u7528\u3002<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"","ping_status":"open","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4],"tags":[102,86,105,103,6],"class_list":["post-294","post","type-post","status-publish","format-standard","hentry","category-4","tag-asyncio","tag-python","tag-105","tag-103","tag-6"],"_links":{"self":[{"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/posts\/294","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/yykcj.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcomments&post=294"}],"version-history":[{"count":0,"href":"https:\/\/yykcj.com\/index.php?rest_route=\/wp\/v2\/posts\/294\/revisions"}],"wp:attachment":[{"href":"https:\/\/yykcj.com\/index.php?rest_route=%2Fwp%2Fv2%2Fmedia&parent=294"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/yykcj.com\/index.php?rest_route=%2Fwp%2Fv2%2Fcategories&post=294"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/yykcj.com\/index.php?rest_route=%2Fwp%2Fv2%2Ftags&post=294"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}