[{"data":1,"prerenderedAt":3576},["ShallowReactive",2],{"blog-python-gil-introduction":3,"related-python-gil-introduction":432},{"id":4,"title":5,"author":6,"body":7,"category":416,"date":417,"description":418,"draft":419,"extension":420,"image":402,"meta":421,"navigation":422,"path":423,"seo":424,"stem":425,"tags":426,"__hash__":431},"blog/blog/python-gil-introduction.md","Python GIL 介紹","Ting Zhang",{"type":8,"value":9,"toc":401},"minimark",[10,15,22,25,48,51,55,60,65,85,89,92,169,173,176,251,255,258,284,287,307,310,366,369],[11,12,14],"h2",{"id":13},"什麼是-gil","什麼是 GIL？",[16,17,18],"blockquote",{},[19,20,21],"p",{},"💡 GIL 是 CPython 解釋器中的一個鎖，確保在任何時刻只有一個線程可以執行 Python 字節碼。",[19,23,24],{},"這意味著即使有多個線程，Python 程式也無法真正利用多核心 CPU 實現並行（parallelism），僅能實現並發（concurrency）的假象。GIL 為 Python 提供了以下好處：",[26,27,28,36,42],"ul",{},[29,30,31,35],"li",{},[32,33,34],"strong",{},"簡化種族條件（Race Conditions）","：防止Multi thread同時修改共享資料，降低記憶體損壞風險。",[29,37,38,41],{},[32,39,40],{},"簡化垃圾回收（Garbage Collection）","：GIL 使記憶體管理更簡單，無需複雜的鎖機制。",[29,43,44,47],{},[32,45,46],{},"歷史背景","：Python 於 1991 年設計時，多數電腦僅有單核心 CPU，GIL 是當時簡化實現的合理選擇。",[19,49,50],{},"然而，GIL 的缺點顯而易見：它限制了多核心 CPU 的利用率，使 Python 在 CPU 密集型任務（如數學計算、資料解析、AI 模型訓練）上的效能不如預期。",[11,52,54],{"id":53},"為什麼移除-gilpep-703-python-313","為什麼移除 GIL？（PEP 703, Python 3.13）",[16,56,57],{},[19,58,59],{},"💡 隨著硬體技術的進步（多核心 CPU 普及）和 Python 社群對高效能的需求，GIL 逐漸成為瓶頸。PEP 703（Python 3.13）提出使 GIL 可選，允許程式在編譯時或運行時禁用 GIL，讓Multi thread直接利用操作系統的線程調度器，實現真正的並行。",[61,62,64],"h3",{"id":63},"移除-gil-的動機","移除 GIL 的動機",[26,66,67,73,79],{},[29,68,69,72],{},[32,70,71],{},"社群需求","：開發者希望 Python 能更快，並充分利用現代多核心硬體。",[29,74,75,78],{},[32,76,77],{},"效能提升","：禁用 GIL 後，某些 CPU 密集型任務（如桶排序、分形生成）可顯著加速。",[29,80,81,84],{},[32,82,83],{},"競爭壓力","：其他語言（如 Go、Rust）支援真正的並行，Python 需跟上時代。",[61,86,88],{"id":87},"移除-gil-的挑戰","移除 GIL 的挑戰",[19,90,91],{},"移除 GIL 並非易事，因為 Python 的許多核心機制依賴 GIL 的保護。以下是主要挑戰：",[93,94,95,128,140,157],"ol",{},[29,96,97,100],{},[32,98,99],{},"引用計數（Reference Counting）",[26,101,102,108],{},[29,103,104,107],{},[32,105,106],{},"問題","：傳統的非原子引用計數（non-atomic reference counting）不具線程安全，可能導致種族條件。例如，refcount++ 分三步（讀、加、寫），可能被其他線程中斷。",[29,109,110,113,114],{},[32,111,112],{},"解決方案","：\n",[26,115,116,122],{},[29,117,118,121],{},[32,119,120],{},"原子引用計數","：線程安全，但速度慢 10x-100x。",[29,123,124,127],{},[32,125,126],{},"偏向引用計數（Biased Reference Counting）","：檢查引用是否僅屬於單一線程，若是則使用快速的非原子計數，否則使用原子計數。",[29,129,130,133],{},[32,131,132],{},"垃圾回收（Garbage Collection）",[26,134,135],{},[29,136,137,139],{},[32,138,106],{},"：傳統垃圾回收依賴 GIL 保護，需改用延遲引用計數（deferred reference counting）來處理循環引用。",[29,141,142,145],{},[32,143,144],{},"記憶體分配",[26,146,147,152],{},[29,148,149,151],{},[32,150,106],{},"：現有記憶體分配器假設 GIL 保護，不具線程安全。",[29,153,154,156],{},[32,155,112],{},"：開發新的線程安全記憶體分配器，優化列表和字典的快速讀取。",[29,158,159,162],{},[32,160,161],{},"兼容性",[26,163,164],{},[29,165,166,168],{},[32,167,106],{},"：許多 C-API 擴展（如 NumPy、Pandas）假設 GIL 存在，需重新編譯以支援無 GIL 環境。",[11,170,172],{"id":171},"gil-與禁用-gil-的比較","GIL 與禁用 GIL 的比較",[19,174,175],{},"以下表格比較了 GIL 和禁用 GIL 的特點：",[177,178,179,195],"table",{},[180,181,182],"thead",{},[183,184,185,189,192],"tr",{},[186,187,188],"th",{},"特性",[186,190,191],{},"啟用 GIL",[186,193,194],{},"禁用 GIL",[196,197,198,212,225,238],"tbody",{},[183,199,200,206,209],{},[201,202,203],"td",{},[32,204,205],{},"並行性",[201,207,208],{},"非真正的並行，僅一個線程執行",[201,210,211],{},"真正的Multi thread並行，利用多核心",[183,213,214,219,222],{},[201,215,216],{},[32,217,218],{},"資料共享",[201,220,221],{},"簡單，無需額外鎖",[201,223,224],{},"需小心處理種族條件（如使用 threading.Lock）",[183,226,227,232,235],{},[201,228,229],{},[32,230,231],{},"效能",[201,233,234],{},"受限於 GIL，CPU 綁定任務慢",[201,236,237],{},"視程式而定，可能顯著提升（如桶排序、分形生成）",[183,239,240,245,248],{},[201,241,242],{},[32,243,244],{},"擴展相容性",[201,246,247],{},"廣泛支援",[201,249,250],{},"需檢查擴展版本（如 Cython、NumPy）",[11,252,254],{"id":253},"禁用-gil-的推薦場景","禁用 GIL 的推薦場景",[19,256,257],{},"禁用 GIL 在以下場景中特別有用：",[26,259,260,266,272,278],{},[29,261,262,265],{},[32,263,264],{},"ETL 處理","：資料提取、轉換和載入需要大量計算。",[29,267,268,271],{},[32,269,270],{},"圖像處理","：如濾波、轉換等 CPU 密集型操作。",[29,273,274,277],{},[32,275,276],{},"日誌分析","：處理大量資料並進行模式匹配。",[29,279,280,283],{},[32,281,282],{},"即時分析","：需要快速響應的計算任務。",[11,285,286],{"id":286},"注意事項",[26,288,289,295,301],{},[29,290,291,294],{},[32,292,293],{},"Race Condition","：禁用 GIL 後，Multi thread可能同時存取共享資料，導致記憶體損壞。建議使用 threading.Lock 或其他同步機制。",[29,296,297,300],{},[32,298,299],{},"擴展模組相容性","：確認使用的庫（如 NumPy、Pandas、PyTorch）支援無 GIL 環境。",[29,302,303,306],{},[32,304,305],{},"效能不確定性","：禁用 GIL 不保證所有程式都變快，需針對具體任務進行基準測試。",[11,308,309],{"id":309},"常見誤解與解答",[93,311,312,326,336,346,356],{},[29,313,314,317,318],{},[32,315,316],{},"並發(Concurrency)與並行(Parallelism)的區別","：",[26,319,320,323],{},[29,321,322],{},"並發是多任務「看似」同時進行，實際上可能是切換執行。",[29,324,325],{},"並行是多任務在多核心上真正同時執行。",[29,327,328,331],{},[32,329,330],{},"為什麼 Python 慢？",[26,332,333],{},[29,334,335],{},"GIL 限制了Multi thread的並行性，導致 CPU 綁定任務無法充分利用多核心。",[29,337,338,341],{},[32,339,340],{},"禁用 GIL 如何管理 CPU 使用？",[26,342,343],{},[29,344,345],{},"透過操作系統的線程調度器，讓Multi thread在多核心上並行執行。",[29,347,348,351],{},[32,349,350],{},"禁用 GIL 是否總是更快？",[26,352,353],{},[29,354,355],{},"不一定，效能提升取決於任務類型和程式設計。某些任務（如 I/O 綁定）可能無明顯改善。",[29,357,358,361],{},[32,359,360],{},"簡單資料共享是什麼？",[26,362,363],{},[29,364,365],{},"指線程間直接存取記憶體的能力，而Multi process需要管道或共享記憶體，較為複雜。",[11,367,368],{"id":368},"參考資料",[26,370,371,380,387,394],{},[29,372,373],{},[374,375,379],"a",{"href":376,"rel":377},"https://peps.python.org/pep-0703/",[378],"nofollow","PEP 703 – Making the Global Interpreter Lock Optional in CPython",[29,381,382],{},[374,383,386],{"href":384,"rel":385},"https://tw.pycon.org/2025/zh-hant/conference/keynotes#Donghee_Na",[378],"PyCon TW 2025 主題演講",[29,388,389],{},[374,390,393],{"href":391,"rel":392},"https://tw.pycon.org/2025/zh-hant/conference/talk/352",[378],"PyCon TW 2025 - Talk 352",[29,395,396],{},[374,397,400],{"href":398,"rel":399},"https://tw.pycon.org/2025/zh-hant/conference/talk/335",[378],"PyCon TW 2025 - Talk 335",{"title":402,"searchDepth":403,"depth":403,"links":404},"",2,[405,406,411,412,413,414,415],{"id":13,"depth":403,"text":14},{"id":53,"depth":403,"text":54,"children":407},[408,410],{"id":63,"depth":409,"text":64},3,{"id":87,"depth":409,"text":88},{"id":171,"depth":403,"text":172},{"id":253,"depth":403,"text":254},{"id":286,"depth":403,"text":286},{"id":309,"depth":403,"text":309},{"id":368,"depth":403,"text":368},"技術","2025-10-24","Python 全域直譯器鎖（GIL）介紹",false,"md",{},true,"/blog/python-gil-introduction",{"title":5,"description":418},"blog/python-gil-introduction",[427,428,429,430],"Python","GIL","Threading","Concurrency","HEyyMIX4ERxJ70UGu2zKfrzTPLf2cYOCJfUly7xneRo",[433,1897,3233],{"id":434,"title":435,"author":6,"body":436,"category":416,"date":417,"description":1890,"draft":419,"extension":420,"image":402,"meta":1891,"navigation":422,"path":1892,"seo":1893,"stem":1894,"tags":1895,"__hash__":1896},"blog/blog/concurrency.md","Python 並發處理方法",{"type":8,"value":437,"toc":1869},[438,442,445,448,451,455,502,506,539,543,575,579,597,600,741,744,1442,1445,1696,1700,1706,1724,1728,1733,1751,1754,1759,1763,1766,1770,1773,1787,1791,1794,1840,1842,1865],[11,439,441],{"id":440},"這篇文章的用處","這篇文章的用處？",[19,443,444],{},"若專案內有遇到效能瓶頸，這可能可以幫助你加速。",[19,446,447],{},"Python 提供了幾種並發方式，每種方式適用於不同類型的任務。",[11,449,450],{"id":450},"各方式介紹",[61,452,454],{"id":453},"_1-多線程multithreading","1. 多線程（Multithreading）",[26,456,457,463,484,490,496],{},[29,458,459,462],{},[32,460,461],{},"特點","：由於 GIL 的存在，多線程無法實現真正的並行，線程間由解釋器切換執行。",[29,464,465,468,469,472,473],{},[32,466,467],{},"適用場景","：適合 ",[32,470,471],{},"I/O 綁定任務","，如：\n",[26,474,475,478,481],{},[29,476,477],{},"API 呼叫",[29,479,480],{},"檔案讀寫",[29,482,483],{},"使用者輸入等待",[29,485,486,489],{},[32,487,488],{},"限制","：在 CPU 綁定任務（如計算 Fibonacci 數列）中，效能與單線程迴圈相差無幾。",[29,491,492,495],{},[32,493,494],{},"優點","：線程間資料共享簡單，記憶體開銷低。",[29,497,498,501],{},[32,499,500],{},"缺點","：受 GIL 限制，無法利用多核心。",[61,503,505],{"id":504},"_2-多進程multiprocessing","2. 多進程（Multiprocessing）",[26,507,508,513,529,534],{},[29,509,510,512],{},[32,511,461],{},"：每個進程擁有獨立的 Python 解釋器和 GIL，因此可以在不同 CPU 核心上實現真正的並行。",[29,514,515,468,517,472,520],{},[32,516,467],{},[32,518,519],{},"CPU 綁定任務",[26,521,522,525,527],{},[29,523,524],{},"數學運算",[29,526,270],{},[29,528,276],{},[29,530,531,533],{},[32,532,494],{},"：繞過 GIL，實現真並行，速度較快。",[29,535,536,538],{},[32,537,500],{},"：記憶體使用量高，進程間資料共享較複雜（需使用管道或共享記憶體）。",[61,540,542],{"id":541},"_3-asyncio","3. Asyncio",[26,544,545,550,565,570],{},[29,546,547,549],{},[32,548,461],{},"：使用協程（coroutines）實現非阻塞的並發，適合 I/O 綁定任務。",[29,551,552,113,554],{},[32,553,467],{},[26,555,556,559,562],{},[29,557,558],{},"網路請求",[29,560,561],{},"檔案 I/O",[29,563,564],{},"其他等待外部資源的任務",[29,566,567,569],{},[32,568,494],{},"：輕量，記憶體使用效率高。",[29,571,572,574],{},[32,573,500],{},"：不適合 CPU 密集型任務，因為它並非真正的並行。",[61,576,578],{"id":577},"_4-第三方庫","4. 第三方庫",[26,580,581,587,592],{},[29,582,583,586],{},[32,584,585],{},"例子","：Cython、NumPy、Pandas、PyTorch 等。",[29,588,589,591],{},[32,590,461],{},"：這些庫通常使用 C 語言實現，部分操作可繞過 GIL，提供高效能。",[29,593,594,596],{},[32,595,467],{},"：特定計算密集型任務（如矩陣運算）。",[11,598,599],{"id":599},"特性比較表",[177,601,602,620],{},[180,603,604],{},[183,605,606,608,611,614,617],{},[186,607,188],{},[186,609,610],{},"Multi-threading",[186,612,613],{},"Multi-processing",[186,615,616],{},"AsyncIO",[186,618,619],{},"Disabled GIL",[196,621,622,639,656,674,691,707,722],{},[183,623,624,629,632,635,637],{},[201,625,626],{},[32,627,628],{},"並行",[201,630,631],{},"❌",[201,633,634],{},"✅",[201,636,631],{},[201,638,634],{},[183,640,641,646,649,652,654],{},[201,642,643],{},[32,644,645],{},"記憶體共享",[201,647,648],{},"容易",[201,650,651],{},"困難",[201,653,648],{},[201,655,648],{},[183,657,658,663,666,669,671],{},[201,659,660],{},[32,661,662],{},"記憶體使用",[201,664,665],{},"低",[201,667,668],{},"高",[201,670,665],{},[201,672,673],{},"中等",[183,675,676,681,684,687,689],{},[201,677,678],{},[32,679,680],{},"CPU 密集型",[201,682,683],{},"差",[201,685,686],{},"好",[201,688,683],{},[201,690,686],{},[183,692,693,698,700,702,705],{},[201,694,695],{},[32,696,697],{},"I/O 密集型",[201,699,686],{},[201,701,673],{},[201,703,704],{},"最佳",[201,706,686],{},[183,708,709,714,716,718,720],{},[201,710,711],{},[32,712,713],{},"實作複雜度",[201,715,673],{},[201,717,668],{},[201,719,673],{},[201,721,668],{},[183,723,724,729,732,735,738],{},[201,725,726],{},[32,727,728],{},"競爭條件風險",[201,730,731],{},"低（GIL保護）",[201,733,734],{},"低（隔離）",[201,736,737],{},"無（單執行緒）",[201,739,740],{},"高（需手動處理）",[11,742,743],{"id":743},"範例程式碼",[745,746,750],"pre",{"className":747,"code":748,"language":749,"meta":402,"style":402},"language-python shiki shiki-themes github-light github-dark","import time\nimport threading\nimport multiprocessing\nimport asyncio\nimport sys\nfrom concurrent.futures import ThreadPoolExecutor\nfrom functools import wraps\n\n# 計時裝飾器，用於測量執行時間\ndef timing_decorator(func):\n    @wraps(func)\n    def wrapper(*args, **kwargs):\n        start = time.time()\n        result = func(*args, **kwargs)\n        end = time.time()\n        print(f\"{func.__name__} 執行時間: {end - start:.4f} 秒\")\n        return result\n    return wrapper\n\n# CPU 密集型任務：計算 Fibonacci 數列\ndef fib(n):\n    if n \u003C= 1:\n        return n\n    return fib(n - 1) + fib(n - 2)\n\n# I/O 綁定任務：模擬網路請求（全局函數）\ndef sync_io_task():\n    time.sleep(1)  # 模擬 1 秒的 I/O 延遲\n\n# 異步 I/O 任務\nasync def io_bound_task():\n    await asyncio.sleep(1)  # 模擬 1 秒的 I/O 延遲\n    return \"I/O 任務完成\"\n\n# 多線程實現\n@timing_decorator\ndef run_multithreading(n_tasks, task_type=\"cpu\"):\n    threads = []\n    if task_type == \"cpu\":\n        for _ in range(n_tasks):\n            t = threading.Thread(target=fib, args=(35,))\n            threads.append(t)\n            t.start()\n        for t in threads:\n            t.join()\n    else:  # I/O 任務\n        for _ in range(n_tasks):\n            t = threading.Thread(target=sync_io_task)\n            threads.append(t)\n            t.start()\n        for t in threads:\n            t.join()\n\n# 多進程實現\n@timing_decorator\ndef run_multiprocessing(n_tasks, task_type=\"cpu\"):\n    processes = []\n    if task_type == \"cpu\":\n        for _ in range(n_tasks):\n            p = multiprocessing.Process(target=fib, args=(35,))\n            processes.append(p)\n            p.start()\n        for p in processes:\n            p.join()\n    else:  # I/O 任務\n        for _ in range(n_tasks):\n            p = multiprocessing.Process(target=sync_io_task)\n            processes.append(p)\n            p.start()\n        for p in processes:\n            p.join()\n\n# Asyncio 實現\n@timing_decorator\nasync def run_asyncio(n_tasks):\n    tasks = [io_bound_task() for _ in range(n_tasks)]\n    await asyncio.gather(*tasks)\n\n# 禁用 GIL 的多線程實現（需 Python 3.13 --disable-gil）\n@timing_decorator\ndef run_nogil_multithreading(n_tasks, task_type=\"cpu\"):\n    with ThreadPoolExecutor(max_workers=n_tasks) as executor:\n        if task_type == \"cpu\":\n            futures = [executor.submit(fib, 35) for _ in range(n_tasks)]\n        else:  # I/O 任務\n            futures = [executor.submit(sync_io_task) for _ in range(n_tasks)]\n        for future in futures:\n            future.result()\n\n# 主程式\nif __name__ == \"__main__\":\n    n_tasks = 4  # 任務數量\n\n    print(\"=== CPU 密集型任務 (計算 Fibonacci 數列) ===\")\n    print(\"多線程 (Multithreading):\")\n    run_multithreading(n_tasks, task_type=\"cpu\")\n\n    print(\"\\n多進程 (Multiprocessing):\")\n    run_multiprocessing(n_tasks, task_type=\"cpu\")\n\n    if sys.version_info >= (3, 13) and hasattr(sys, \"disable_gil\"):\n        print(\"\\n禁用 GIL 的多線程:\")\n        run_nogil_multithreading(n_tasks, task_type=\"cpu\")\n    else:\n        print(\"\\n禁用 GIL 的多線程: 需要 Python 3.13 並啟用 --disable-gil\")\n\n    print(\"\\n=== I/O 綁定任務 (模擬網路請求) ===\")\n    print(\"多線程 (Multithreading):\")\n    run_multithreading(n_tasks, task_type=\"io\")\n\n    print(\"\\n多進程 (Multiprocessing):\")\n    run_multiprocessing(n_tasks, task_type=\"io\")\n\n    print(\"\\nAsyncio:\")\n    asyncio.run(run_asyncio(n_tasks))\n\n    if sys.version_info >= (3, 13) and hasattr(sys, \"disable_gil\"):\n        print(\"\\n禁用 GIL 的多線程:\")\n        run_nogil_multithreading(n_tasks, task_type=\"io\")\n    else:\n        print(\"\\n禁用 GIL 的多線程: 需要 Python 3.13 並啟用 --disable-gil\")\n","python",[751,752,753,761,766,771,777,783,789,795,801,807,813,819,825,831,837,843,849,855,861,866,872,878,884,890,896,901,907,913,919,924,930,936,942,948,953,959,965,971,977,983,989,995,1001,1007,1013,1019,1025,1030,1036,1041,1046,1051,1056,1061,1067,1072,1078,1084,1089,1094,1100,1106,1112,1118,1124,1129,1134,1140,1145,1150,1155,1160,1165,1171,1176,1182,1188,1194,1199,1205,1210,1216,1222,1228,1234,1240,1246,1252,1258,1263,1269,1275,1281,1286,1292,1298,1304,1309,1315,1321,1326,1332,1338,1344,1350,1356,1361,1367,1372,1378,1383,1388,1394,1399,1405,1411,1416,1421,1426,1432,1437],"code",{"__ignoreMap":402},[754,755,758],"span",{"class":756,"line":757},"line",1,[754,759,760],{},"import time\n",[754,762,763],{"class":756,"line":403},[754,764,765],{},"import threading\n",[754,767,768],{"class":756,"line":409},[754,769,770],{},"import multiprocessing\n",[754,772,774],{"class":756,"line":773},4,[754,775,776],{},"import asyncio\n",[754,778,780],{"class":756,"line":779},5,[754,781,782],{},"import sys\n",[754,784,786],{"class":756,"line":785},6,[754,787,788],{},"from concurrent.futures import ThreadPoolExecutor\n",[754,790,792],{"class":756,"line":791},7,[754,793,794],{},"from functools import wraps\n",[754,796,798],{"class":756,"line":797},8,[754,799,800],{"emptyLinePlaceholder":422},"\n",[754,802,804],{"class":756,"line":803},9,[754,805,806],{},"# 計時裝飾器，用於測量執行時間\n",[754,808,810],{"class":756,"line":809},10,[754,811,812],{},"def timing_decorator(func):\n",[754,814,816],{"class":756,"line":815},11,[754,817,818],{},"    @wraps(func)\n",[754,820,822],{"class":756,"line":821},12,[754,823,824],{},"    def wrapper(*args, **kwargs):\n",[754,826,828],{"class":756,"line":827},13,[754,829,830],{},"        start = time.time()\n",[754,832,834],{"class":756,"line":833},14,[754,835,836],{},"        result = func(*args, **kwargs)\n",[754,838,840],{"class":756,"line":839},15,[754,841,842],{},"        end = time.time()\n",[754,844,846],{"class":756,"line":845},16,[754,847,848],{},"        print(f\"{func.__name__} 執行時間: {end - start:.4f} 秒\")\n",[754,850,852],{"class":756,"line":851},17,[754,853,854],{},"        return result\n",[754,856,858],{"class":756,"line":857},18,[754,859,860],{},"    return wrapper\n",[754,862,864],{"class":756,"line":863},19,[754,865,800],{"emptyLinePlaceholder":422},[754,867,869],{"class":756,"line":868},20,[754,870,871],{},"# CPU 密集型任務：計算 Fibonacci 數列\n",[754,873,875],{"class":756,"line":874},21,[754,876,877],{},"def fib(n):\n",[754,879,881],{"class":756,"line":880},22,[754,882,883],{},"    if n \u003C= 1:\n",[754,885,887],{"class":756,"line":886},23,[754,888,889],{},"        return n\n",[754,891,893],{"class":756,"line":892},24,[754,894,895],{},"    return fib(n - 1) + fib(n - 2)\n",[754,897,899],{"class":756,"line":898},25,[754,900,800],{"emptyLinePlaceholder":422},[754,902,904],{"class":756,"line":903},26,[754,905,906],{},"# I/O 綁定任務：模擬網路請求（全局函數）\n",[754,908,910],{"class":756,"line":909},27,[754,911,912],{},"def sync_io_task():\n",[754,914,916],{"class":756,"line":915},28,[754,917,918],{},"    time.sleep(1)  # 模擬 1 秒的 I/O 延遲\n",[754,920,922],{"class":756,"line":921},29,[754,923,800],{"emptyLinePlaceholder":422},[754,925,927],{"class":756,"line":926},30,[754,928,929],{},"# 異步 I/O 任務\n",[754,931,933],{"class":756,"line":932},31,[754,934,935],{},"async def io_bound_task():\n",[754,937,939],{"class":756,"line":938},32,[754,940,941],{},"    await asyncio.sleep(1)  # 模擬 1 秒的 I/O 延遲\n",[754,943,945],{"class":756,"line":944},33,[754,946,947],{},"    return \"I/O 任務完成\"\n",[754,949,951],{"class":756,"line":950},34,[754,952,800],{"emptyLinePlaceholder":422},[754,954,956],{"class":756,"line":955},35,[754,957,958],{},"# 多線程實現\n",[754,960,962],{"class":756,"line":961},36,[754,963,964],{},"@timing_decorator\n",[754,966,968],{"class":756,"line":967},37,[754,969,970],{},"def run_multithreading(n_tasks, task_type=\"cpu\"):\n",[754,972,974],{"class":756,"line":973},38,[754,975,976],{},"    threads = []\n",[754,978,980],{"class":756,"line":979},39,[754,981,982],{},"    if task_type == \"cpu\":\n",[754,984,986],{"class":756,"line":985},40,[754,987,988],{},"        for _ in range(n_tasks):\n",[754,990,992],{"class":756,"line":991},41,[754,993,994],{},"            t = threading.Thread(target=fib, args=(35,))\n",[754,996,998],{"class":756,"line":997},42,[754,999,1000],{},"            threads.append(t)\n",[754,1002,1004],{"class":756,"line":1003},43,[754,1005,1006],{},"            t.start()\n",[754,1008,1010],{"class":756,"line":1009},44,[754,1011,1012],{},"        for t in threads:\n",[754,1014,1016],{"class":756,"line":1015},45,[754,1017,1018],{},"            t.join()\n",[754,1020,1022],{"class":756,"line":1021},46,[754,1023,1024],{},"    else:  # I/O 任務\n",[754,1026,1028],{"class":756,"line":1027},47,[754,1029,988],{},[754,1031,1033],{"class":756,"line":1032},48,[754,1034,1035],{},"            t = threading.Thread(target=sync_io_task)\n",[754,1037,1039],{"class":756,"line":1038},49,[754,1040,1000],{},[754,1042,1044],{"class":756,"line":1043},50,[754,1045,1006],{},[754,1047,1049],{"class":756,"line":1048},51,[754,1050,1012],{},[754,1052,1054],{"class":756,"line":1053},52,[754,1055,1018],{},[754,1057,1059],{"class":756,"line":1058},53,[754,1060,800],{"emptyLinePlaceholder":422},[754,1062,1064],{"class":756,"line":1063},54,[754,1065,1066],{},"# 多進程實現\n",[754,1068,1070],{"class":756,"line":1069},55,[754,1071,964],{},[754,1073,1075],{"class":756,"line":1074},56,[754,1076,1077],{},"def run_multiprocessing(n_tasks, task_type=\"cpu\"):\n",[754,1079,1081],{"class":756,"line":1080},57,[754,1082,1083],{},"    processes = []\n",[754,1085,1087],{"class":756,"line":1086},58,[754,1088,982],{},[754,1090,1092],{"class":756,"line":1091},59,[754,1093,988],{},[754,1095,1097],{"class":756,"line":1096},60,[754,1098,1099],{},"            p = multiprocessing.Process(target=fib, args=(35,))\n",[754,1101,1103],{"class":756,"line":1102},61,[754,1104,1105],{},"            processes.append(p)\n",[754,1107,1109],{"class":756,"line":1108},62,[754,1110,1111],{},"            p.start()\n",[754,1113,1115],{"class":756,"line":1114},63,[754,1116,1117],{},"        for p in processes:\n",[754,1119,1121],{"class":756,"line":1120},64,[754,1122,1123],{},"            p.join()\n",[754,1125,1127],{"class":756,"line":1126},65,[754,1128,1024],{},[754,1130,1132],{"class":756,"line":1131},66,[754,1133,988],{},[754,1135,1137],{"class":756,"line":1136},67,[754,1138,1139],{},"            p = multiprocessing.Process(target=sync_io_task)\n",[754,1141,1143],{"class":756,"line":1142},68,[754,1144,1105],{},[754,1146,1148],{"class":756,"line":1147},69,[754,1149,1111],{},[754,1151,1153],{"class":756,"line":1152},70,[754,1154,1117],{},[754,1156,1158],{"class":756,"line":1157},71,[754,1159,1123],{},[754,1161,1163],{"class":756,"line":1162},72,[754,1164,800],{"emptyLinePlaceholder":422},[754,1166,1168],{"class":756,"line":1167},73,[754,1169,1170],{},"# Asyncio 實現\n",[754,1172,1174],{"class":756,"line":1173},74,[754,1175,964],{},[754,1177,1179],{"class":756,"line":1178},75,[754,1180,1181],{},"async def run_asyncio(n_tasks):\n",[754,1183,1185],{"class":756,"line":1184},76,[754,1186,1187],{},"    tasks = [io_bound_task() for _ in range(n_tasks)]\n",[754,1189,1191],{"class":756,"line":1190},77,[754,1192,1193],{},"    await asyncio.gather(*tasks)\n",[754,1195,1197],{"class":756,"line":1196},78,[754,1198,800],{"emptyLinePlaceholder":422},[754,1200,1202],{"class":756,"line":1201},79,[754,1203,1204],{},"# 禁用 GIL 的多線程實現（需 Python 3.13 --disable-gil）\n",[754,1206,1208],{"class":756,"line":1207},80,[754,1209,964],{},[754,1211,1213],{"class":756,"line":1212},81,[754,1214,1215],{},"def run_nogil_multithreading(n_tasks, task_type=\"cpu\"):\n",[754,1217,1219],{"class":756,"line":1218},82,[754,1220,1221],{},"    with ThreadPoolExecutor(max_workers=n_tasks) as executor:\n",[754,1223,1225],{"class":756,"line":1224},83,[754,1226,1227],{},"        if task_type == \"cpu\":\n",[754,1229,1231],{"class":756,"line":1230},84,[754,1232,1233],{},"            futures = [executor.submit(fib, 35) for _ in range(n_tasks)]\n",[754,1235,1237],{"class":756,"line":1236},85,[754,1238,1239],{},"        else:  # I/O 任務\n",[754,1241,1243],{"class":756,"line":1242},86,[754,1244,1245],{},"            futures = [executor.submit(sync_io_task) for _ in range(n_tasks)]\n",[754,1247,1249],{"class":756,"line":1248},87,[754,1250,1251],{},"        for future in futures:\n",[754,1253,1255],{"class":756,"line":1254},88,[754,1256,1257],{},"            future.result()\n",[754,1259,1261],{"class":756,"line":1260},89,[754,1262,800],{"emptyLinePlaceholder":422},[754,1264,1266],{"class":756,"line":1265},90,[754,1267,1268],{},"# 主程式\n",[754,1270,1272],{"class":756,"line":1271},91,[754,1273,1274],{},"if __name__ == \"__main__\":\n",[754,1276,1278],{"class":756,"line":1277},92,[754,1279,1280],{},"    n_tasks = 4  # 任務數量\n",[754,1282,1284],{"class":756,"line":1283},93,[754,1285,800],{"emptyLinePlaceholder":422},[754,1287,1289],{"class":756,"line":1288},94,[754,1290,1291],{},"    print(\"=== CPU 密集型任務 (計算 Fibonacci 數列) ===\")\n",[754,1293,1295],{"class":756,"line":1294},95,[754,1296,1297],{},"    print(\"多線程 (Multithreading):\")\n",[754,1299,1301],{"class":756,"line":1300},96,[754,1302,1303],{},"    run_multithreading(n_tasks, task_type=\"cpu\")\n",[754,1305,1307],{"class":756,"line":1306},97,[754,1308,800],{"emptyLinePlaceholder":422},[754,1310,1312],{"class":756,"line":1311},98,[754,1313,1314],{},"    print(\"\\n多進程 (Multiprocessing):\")\n",[754,1316,1318],{"class":756,"line":1317},99,[754,1319,1320],{},"    run_multiprocessing(n_tasks, task_type=\"cpu\")\n",[754,1322,1324],{"class":756,"line":1323},100,[754,1325,800],{"emptyLinePlaceholder":422},[754,1327,1329],{"class":756,"line":1328},101,[754,1330,1331],{},"    if sys.version_info >= (3, 13) and hasattr(sys, \"disable_gil\"):\n",[754,1333,1335],{"class":756,"line":1334},102,[754,1336,1337],{},"        print(\"\\n禁用 GIL 的多線程:\")\n",[754,1339,1341],{"class":756,"line":1340},103,[754,1342,1343],{},"        run_nogil_multithreading(n_tasks, task_type=\"cpu\")\n",[754,1345,1347],{"class":756,"line":1346},104,[754,1348,1349],{},"    else:\n",[754,1351,1353],{"class":756,"line":1352},105,[754,1354,1355],{},"        print(\"\\n禁用 GIL 的多線程: 需要 Python 3.13 並啟用 --disable-gil\")\n",[754,1357,1359],{"class":756,"line":1358},106,[754,1360,800],{"emptyLinePlaceholder":422},[754,1362,1364],{"class":756,"line":1363},107,[754,1365,1366],{},"    print(\"\\n=== I/O 綁定任務 (模擬網路請求) ===\")\n",[754,1368,1370],{"class":756,"line":1369},108,[754,1371,1297],{},[754,1373,1375],{"class":756,"line":1374},109,[754,1376,1377],{},"    run_multithreading(n_tasks, task_type=\"io\")\n",[754,1379,1381],{"class":756,"line":1380},110,[754,1382,800],{"emptyLinePlaceholder":422},[754,1384,1386],{"class":756,"line":1385},111,[754,1387,1314],{},[754,1389,1391],{"class":756,"line":1390},112,[754,1392,1393],{},"    run_multiprocessing(n_tasks, task_type=\"io\")\n",[754,1395,1397],{"class":756,"line":1396},113,[754,1398,800],{"emptyLinePlaceholder":422},[754,1400,1402],{"class":756,"line":1401},114,[754,1403,1404],{},"    print(\"\\nAsyncio:\")\n",[754,1406,1408],{"class":756,"line":1407},115,[754,1409,1410],{},"    asyncio.run(run_asyncio(n_tasks))\n",[754,1412,1414],{"class":756,"line":1413},116,[754,1415,800],{"emptyLinePlaceholder":422},[754,1417,1419],{"class":756,"line":1418},117,[754,1420,1331],{},[754,1422,1424],{"class":756,"line":1423},118,[754,1425,1337],{},[754,1427,1429],{"class":756,"line":1428},119,[754,1430,1431],{},"        run_nogil_multithreading(n_tasks, task_type=\"io\")\n",[754,1433,1435],{"class":756,"line":1434},120,[754,1436,1349],{},[754,1438,1440],{"class":756,"line":1439},121,[754,1441,1355],{},[11,1443,1444],{"id":1444},"執行結果分析",[745,1446,1450],{"className":1447,"code":1448,"language":1449,"meta":402,"style":402},"language-bash shiki shiki-themes github-light github-dark","$ uv run --no-project --python 3.13.5+freethreaded test.py\n\n=== CPU 密集型任務 (計算 Fibonacci 數列) ===\n多線程 (Multithreading):\nrun_multithreading 執行時間: 0.8912 秒\n\n多進程 (Multiprocessing):\nrun_multiprocessing 執行時間: 1.0846 秒\n\n禁用 GIL 的多線程:\nGIL 狀態: 禁用\nrun_nogil_multithreading 執行時間: 0.8713 秒\n\n=== I/O 綁定任務 (模擬網路請求) ===\n多線程 (Multithreading):\nrun_multithreading 執行時間: 1.0072 秒\n\n多進程 (Multiprocessing):\nrun_multiprocessing 執行時間: 1.1046 秒\n\nAsyncio:\nrun_asyncio 執行時間: 0.0000 秒\n\n禁用 GIL 的多線程:\nGIL 狀態: 禁用\nrun_nogil_multithreading 執行時間: 1.0093 秒\n","bash",[751,1451,1452,1478,1482,1506,1514,1528,1532,1540,1552,1556,1567,1577,1589,1593,1606,1612,1623,1627,1633,1644,1648,1653,1665,1669,1677,1685],{"__ignoreMap":402},[754,1453,1454,1458,1462,1465,1469,1472,1475],{"class":756,"line":757},[754,1455,1457],{"class":1456},"sScJk","$",[754,1459,1461],{"class":1460},"sZZnC"," uv",[754,1463,1464],{"class":1460}," run",[754,1466,1468],{"class":1467},"sj4cs"," --no-project",[754,1470,1471],{"class":1467}," --python",[754,1473,1474],{"class":1460}," 3.13.5+freethreaded",[754,1476,1477],{"class":1460}," test.py\n",[754,1479,1480],{"class":756,"line":403},[754,1481,800],{"emptyLinePlaceholder":422},[754,1483,1484,1487,1490,1493,1497,1500,1503],{"class":756,"line":409},[754,1485,1486],{"class":1460},"===",[754,1488,1489],{"class":1460}," CPU",[754,1491,1492],{"class":1460}," 密集型任務",[754,1494,1496],{"class":1495},"sVt8B"," (計算 ",[754,1498,1499],{"class":1460},"Fibonacci",[754,1501,1502],{"class":1460}," 數列",[754,1504,1505],{"class":1495},") ===\n",[754,1507,1508,1511],{"class":756,"line":773},[754,1509,1510],{"class":1456},"多線程",[754,1512,1513],{"class":1495}," (Multithreading):\n",[754,1515,1516,1519,1522,1525],{"class":756,"line":779},[754,1517,1518],{"class":1456},"run_multithreading",[754,1520,1521],{"class":1460}," 執行時間:",[754,1523,1524],{"class":1467}," 0.8912",[754,1526,1527],{"class":1460}," 秒\n",[754,1529,1530],{"class":756,"line":785},[754,1531,800],{"emptyLinePlaceholder":422},[754,1533,1534,1537],{"class":756,"line":791},[754,1535,1536],{"class":1456},"多進程",[754,1538,1539],{"class":1495}," (Multiprocessing):\n",[754,1541,1542,1545,1547,1550],{"class":756,"line":797},[754,1543,1544],{"class":1456},"run_multiprocessing",[754,1546,1521],{"class":1460},[754,1548,1549],{"class":1467}," 1.0846",[754,1551,1527],{"class":1460},[754,1553,1554],{"class":756,"line":803},[754,1555,800],{"emptyLinePlaceholder":422},[754,1557,1558,1561,1564],{"class":756,"line":809},[754,1559,1560],{"class":1456},"禁用",[754,1562,1563],{"class":1460}," GIL",[754,1565,1566],{"class":1460}," 的多線程:\n",[754,1568,1569,1571,1574],{"class":756,"line":815},[754,1570,428],{"class":1456},[754,1572,1573],{"class":1460}," 狀態:",[754,1575,1576],{"class":1460}," 禁用\n",[754,1578,1579,1582,1584,1587],{"class":756,"line":821},[754,1580,1581],{"class":1456},"run_nogil_multithreading",[754,1583,1521],{"class":1460},[754,1585,1586],{"class":1467}," 0.8713",[754,1588,1527],{"class":1460},[754,1590,1591],{"class":756,"line":827},[754,1592,800],{"emptyLinePlaceholder":422},[754,1594,1595,1597,1600,1603],{"class":756,"line":833},[754,1596,1486],{"class":1460},[754,1598,1599],{"class":1460}," I/O",[754,1601,1602],{"class":1460}," 綁定任務",[754,1604,1605],{"class":1495}," (模擬網路請求) ===\n",[754,1607,1608,1610],{"class":756,"line":839},[754,1609,1510],{"class":1456},[754,1611,1513],{"class":1495},[754,1613,1614,1616,1618,1621],{"class":756,"line":845},[754,1615,1518],{"class":1456},[754,1617,1521],{"class":1460},[754,1619,1620],{"class":1467}," 1.0072",[754,1622,1527],{"class":1460},[754,1624,1625],{"class":756,"line":851},[754,1626,800],{"emptyLinePlaceholder":422},[754,1628,1629,1631],{"class":756,"line":857},[754,1630,1536],{"class":1456},[754,1632,1539],{"class":1495},[754,1634,1635,1637,1639,1642],{"class":756,"line":863},[754,1636,1544],{"class":1456},[754,1638,1521],{"class":1460},[754,1640,1641],{"class":1467}," 1.1046",[754,1643,1527],{"class":1460},[754,1645,1646],{"class":756,"line":868},[754,1647,800],{"emptyLinePlaceholder":422},[754,1649,1650],{"class":756,"line":874},[754,1651,1652],{"class":1456},"Asyncio:\n",[754,1654,1655,1658,1660,1663],{"class":756,"line":880},[754,1656,1657],{"class":1456},"run_asyncio",[754,1659,1521],{"class":1460},[754,1661,1662],{"class":1467}," 0.0000",[754,1664,1527],{"class":1460},[754,1666,1667],{"class":756,"line":886},[754,1668,800],{"emptyLinePlaceholder":422},[754,1670,1671,1673,1675],{"class":756,"line":892},[754,1672,1560],{"class":1456},[754,1674,1563],{"class":1460},[754,1676,1566],{"class":1460},[754,1678,1679,1681,1683],{"class":756,"line":898},[754,1680,428],{"class":1456},[754,1682,1573],{"class":1460},[754,1684,1576],{"class":1460},[754,1686,1687,1689,1691,1694],{"class":756,"line":903},[754,1688,1581],{"class":1456},[754,1690,1521],{"class":1460},[754,1692,1693],{"class":1467}," 1.0093",[754,1695,1527],{"class":1460},[61,1697,1699],{"id":1698},"cpu-密集型任務計算-fibonacci-數列","CPU 密集型任務（計算 Fibonacci 數列）",[19,1701,1702,1703],{},"執行時間排序：",[32,1704,1705],{},"GIL Disabled (0.8713 秒) \u003C 多線程 (0.8912 秒) \u003C 多進程 (1.0846 秒)",[26,1707,1708,1713,1718],{},[29,1709,1710,1712],{},[32,1711,1510],{},"：受 GIL 限制，執行速度與單 CPU 執行差不多",[29,1714,1715,1717],{},[32,1716,1536],{},"：運用多個 CPU 核心加速",[29,1719,1720,1723],{},[32,1721,1722],{},"GIL Disabled","：運用多個 CPU 核心加速，且避免了多進程管理的額外開銷",[61,1725,1727],{"id":1726},"io-綁定任務模擬網路請求","I/O 綁定任務（模擬網路請求）",[19,1729,1702,1730],{},[32,1731,1732],{},"Asyncio (0.0000 秒) \u003C\u003C 多線程 (1.0072 秒) ≈ GIL Disabled (1.0093 秒) ≈ 多進程 (1.1046 秒)",[26,1734,1735,1741],{},[29,1736,1737,1740],{},[32,1738,1739],{},"多線程、多進程、GIL Disabled","：三者效能差不多",[29,1742,1743,1746,1747,1750],{},[32,1744,1745],{},"Asyncio","：效能最好，因為測試任務使用 ",[751,1748,1749],{},"await asyncio.sleep","，基本上不會有運行時間開銷",[11,1752,1753],{"id":1753},"實際應用場景",[19,1755,1756],{},[32,1757,1758],{},"首先需要考慮業務場景，做這個優化加速是否有需要？如果加速沒有很重要的話就是一個 Nice to have 的優化。",[61,1760,1762],{"id":1761},"不建議使用-disabled-gil","不建議使用 Disabled GIL",[19,1764,1765],{},"目前 Disabled GIL 還在測試階段，許多套件都還沒完全支援，也需要自己處理變數管理等問題，目前不考慮使用。",[61,1767,1769],{"id":1768},"適合使用-multiprocessing-的場景","適合使用 Multiprocessing 的場景",[19,1771,1772],{},"非 AI 的大量運算需求，可以使用 Multiprocessing 來加速：",[26,1774,1775,1781],{},[29,1776,1777,1780],{},[32,1778,1779],{},"售電平台的最佳參數求取","：目前策略使用網格搜索，可以切分網格分配給 CPU 執行",[29,1782,1783,1786],{},[32,1784,1785],{},"EV 管理平台","：需要定時計算電站使用率",[61,1788,1790],{"id":1789},"適合使用-asyncio-的場景","適合使用 Asyncio 的場景",[19,1792,1793],{},"網路的大量需求，可以使用 Asyncio 來加速：",[26,1795,1796,1802,1820,1830],{},[29,1797,1798,1801],{},[32,1799,1800],{},"MQTT / OCPP","：這類 pub/sub 協議",[29,1803,1804,113,1807],{},[32,1805,1806],{},"爬蟲或大量 Third-party API 請求",[26,1808,1809],{},[29,1810,1811,1812,1815,1816,1819],{},"使用 ",[751,1813,1814],{},"aiohttp"," 替換 ",[751,1817,1818],{},"requests"," 模組",[29,1821,1822,113,1825],{},[32,1823,1824],{},"Database 異步操作",[26,1826,1827],{},[29,1828,1829],{},"pymongo 遷移到 async client (≥ v4.13)",[29,1831,1832,113,1835],{},[32,1833,1834],{},"Web Framework",[26,1836,1837],{},[29,1838,1839],{},"Flask 遷移到 FastAPI",[11,1841,368],{"id":368},[26,1843,1844,1851,1858],{},[29,1845,1846],{},[374,1847,1850],{"href":1848,"rel":1849},"https://www.youtube.com/watch?v=brYsDi-JajI",[378],"【python】asyncio的理解與入門，搞不明白協程？看這個視頻就夠了",[29,1852,1853],{},[374,1854,1857],{"href":1855,"rel":1856},"https://www.youtube.com/watch?v=K0BjgYZbgfE&t=94s",[378],"【python】await機制詳解。再來個硬核內容，把並行和依賴背後的原理全給你講明白",[29,1859,1860],{},[374,1861,1864],{"href":1862,"rel":1863},"https://pymongo.readthedocs.io/en/stable/async-tutorial.html",[378],"Async Tutorial - PyMongo 4.14.1 documentation",[1866,1867,1868],"style",{},"html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .sScJk, html code.shiki .sScJk{--shiki-default:#6F42C1;--shiki-dark:#B392F0}html pre.shiki code .sZZnC, html code.shiki .sZZnC{--shiki-default:#032F62;--shiki-dark:#9ECBFF}html pre.shiki code .sj4cs, html code.shiki .sj4cs{--shiki-default:#005CC5;--shiki-dark:#79B8FF}html pre.shiki code .sVt8B, html code.shiki .sVt8B{--shiki-default:#24292E;--shiki-dark:#E1E4E8}",{"title":402,"searchDepth":403,"depth":403,"links":1870},[1871,1872,1878,1879,1880,1884,1889],{"id":440,"depth":403,"text":441},{"id":450,"depth":403,"text":450,"children":1873},[1874,1875,1876,1877],{"id":453,"depth":409,"text":454},{"id":504,"depth":409,"text":505},{"id":541,"depth":409,"text":542},{"id":577,"depth":409,"text":578},{"id":599,"depth":403,"text":599},{"id":743,"depth":403,"text":743},{"id":1444,"depth":403,"text":1444,"children":1881},[1882,1883],{"id":1698,"depth":409,"text":1699},{"id":1726,"depth":409,"text":1727},{"id":1753,"depth":403,"text":1753,"children":1885},[1886,1887,1888],{"id":1761,"depth":409,"text":1762},{"id":1768,"depth":409,"text":1769},{"id":1789,"depth":409,"text":1790},{"id":368,"depth":403,"text":368},"介紹 Python 並發處理方法，包括多線程、多進程、asyncio 以及其實務應用。",{},"/blog/concurrency",{"title":435,"description":1890},"blog/concurrency",[427,430,429,1745],"1DEoTJ_oFj-_n1U7PDKbn7wPsTmsBUK-5vAp6nZ_s0E",{"id":1898,"title":1899,"author":6,"body":1900,"category":416,"date":417,"description":3223,"draft":419,"extension":420,"image":402,"meta":3224,"navigation":422,"path":3225,"seo":3226,"stem":3227,"tags":3228,"__hash__":3232},"blog/blog/uv-and-ruff.md","uv and Ruff: 最佳的 Python 工具鏈",{"type":8,"value":1901,"toc":3205},[1902,1905,1910,1913,1921,1925,1955,1959,1966,1988,1995,2006,2010,2238,2241,2246,2254,2259,2265,2268,2271,2279,2283,2305,2307,2311,2358,2360,2363,2366,2391,2394,2398,2436,2440,2541,2545,2620,2627,2634,2912,2916,2936,2940,2951,2955,3014,3018,3043,3047,3175,3177,3179,3202],[1903,1904,441],"h1",{"id":440},[16,1906,1907],{},[19,1908,1909],{},"若遇過 format on save 很慢 / 裝環境很麻煩 / 套件衝突，那這篇文章可能對你有用",[1903,1911,1912],{"id":1912},"uv",[16,1914,1915,1918],{},[19,1916,1917],{},"uv 是一個極速的 Python 套件管理器和專案管理工具，被設計為 pip、pip-tools、pipx、poetry、pyenv、virtualenv 等工具的統一替代方案。",[19,1919,1920],{},"uv 的核心理念是提供一個快速、可靠且易用的 Python 工具鏈。",[11,1922,1924],{"id":1923},"uv-的主要特點","uv 的主要特點",[26,1926,1927,1932,1945,1952],{},[29,1928,1929],{},[32,1930,1931],{},"速度極快",[29,1933,1934,1937],{},[32,1935,1936],{},"統一的工作流程",[26,1938,1939,1942],{},[29,1940,1941],{},"整合了套件安裝、虛擬環境管理、專案初始化等功能",[29,1943,1944],{},"一個工具解決多個需求，簡化開發工作流程",[29,1946,1947,1948,1951],{},"確保所有環境部署時依賴相同 (",[751,1949,1950],{},"uv.lock",")",[29,1953,1954],{},"方便切換 python 版本，以及在設定檔中鎖定 python 版本",[11,1956,1958],{"id":1957},"requirementstxt-vs-pyprojecttoml","requirements.txt vs pyproject.toml",[16,1960,1961],{},[19,1962,1963],{},[32,1964,1965],{},"pyproject.toml 是官方標準",[26,1967,1968,1971,1974,1977,1980],{},[29,1969,1970],{},"PEP 518、PEP 621 等官方標準定義的專案配置格式",[29,1972,1973],{},"Python 生態系統的統一標準，未來發展方向",[29,1975,1976],{},"被所有現代工具（pip、uv、poetry、setuptools）支援",[29,1978,1979],{},"可以根據開發、打包、部署等環境分別配置",[29,1981,1982,1983],{},"有 support 的工具都可以統一配置\n",[26,1984,1985],{},[29,1986,1987],{},"例如等等要介紹的 ruff",[16,1989,1990],{},[19,1991,1992],{},[32,1993,1994],{},"requirements.txt 是非正式慣例",[26,1996,1997,2000,2003],{},[29,1998,1999],{},"只是社群約定俗成的做法",[29,2001,2002],{},"沒有正式規範，格式相對簡陋",[29,2004,2005],{},"逐漸被新工具取代",[61,2007,2009],{"id":2008},"範例-pyprojecttoml","範例 pyproject.toml",[745,2011,2015],{"className":2012,"code":2013,"language":2014,"meta":402,"style":402},"language-toml shiki shiki-themes github-light github-dark","[project]\nname = \"my-awesome-project\"\nversion = \"1.0.0\"\ndescription = \"A fantastic Python project\"\nauthors = [{name = \"Your Name\", email = \"you@example.com\"}]\nlicense = {text = \"MIT\"}\nreadme = \"README.md\"\nkeywords = [\"python\", \"awesome\"]\nclassifiers = [\n    \"Development Status :: 4 - Beta\",\n    \"Programming Language :: Python :: 3.11\",\n]\n\n# 依賴管理\ndependencies = [\n    \"requests>=2.28.0\",\n    \"click>=8.0.0\",\n]\n\n# 開發依賴\n[project.optional-dependencies]\ndev = [\n    \"pytest>=7.0.0\",\n    \"ruff>=0.1.0\",\n    \"mypy>=1.0.0\",\n]\ntest = [\n    \"pytest-cov>=4.0.0\",\n    \"pytest-mock>=3.10.0\",\n]\n\n# 工具配置\n[tool.ruff]\nline-length = 88\ntarget-version = \"py311\"\n\n[tool.ruff.lint]\nselect = [\"E\", \"F\", \"UP\", \"B\", \"SIM\", \"I\"]\n\n[tool.pytest.ini_options]\ntestpaths = [\"tests\"]\npython_files = [\"test_*.py\"]\n\n[build-system]\nrequires = [\"setuptools>=61.0\"]\nbuild-backend = \"setuptools.build_meta\"\n","toml",[751,2016,2017,2022,2027,2032,2037,2042,2047,2052,2057,2062,2067,2072,2077,2081,2086,2091,2096,2101,2105,2109,2114,2119,2124,2129,2134,2139,2143,2148,2153,2158,2162,2166,2171,2176,2181,2186,2190,2195,2200,2204,2209,2214,2219,2223,2228,2233],{"__ignoreMap":402},[754,2018,2019],{"class":756,"line":757},[754,2020,2021],{},"[project]\n",[754,2023,2024],{"class":756,"line":403},[754,2025,2026],{},"name = \"my-awesome-project\"\n",[754,2028,2029],{"class":756,"line":409},[754,2030,2031],{},"version = \"1.0.0\"\n",[754,2033,2034],{"class":756,"line":773},[754,2035,2036],{},"description = \"A fantastic Python project\"\n",[754,2038,2039],{"class":756,"line":779},[754,2040,2041],{},"authors = [{name = \"Your Name\", email = \"you@example.com\"}]\n",[754,2043,2044],{"class":756,"line":785},[754,2045,2046],{},"license = {text = \"MIT\"}\n",[754,2048,2049],{"class":756,"line":791},[754,2050,2051],{},"readme = \"README.md\"\n",[754,2053,2054],{"class":756,"line":797},[754,2055,2056],{},"keywords = [\"python\", \"awesome\"]\n",[754,2058,2059],{"class":756,"line":803},[754,2060,2061],{},"classifiers = [\n",[754,2063,2064],{"class":756,"line":809},[754,2065,2066],{},"    \"Development Status :: 4 - Beta\",\n",[754,2068,2069],{"class":756,"line":815},[754,2070,2071],{},"    \"Programming Language :: Python :: 3.11\",\n",[754,2073,2074],{"class":756,"line":821},[754,2075,2076],{},"]\n",[754,2078,2079],{"class":756,"line":827},[754,2080,800],{"emptyLinePlaceholder":422},[754,2082,2083],{"class":756,"line":833},[754,2084,2085],{},"# 依賴管理\n",[754,2087,2088],{"class":756,"line":839},[754,2089,2090],{},"dependencies = [\n",[754,2092,2093],{"class":756,"line":845},[754,2094,2095],{},"    \"requests>=2.28.0\",\n",[754,2097,2098],{"class":756,"line":851},[754,2099,2100],{},"    \"click>=8.0.0\",\n",[754,2102,2103],{"class":756,"line":857},[754,2104,2076],{},[754,2106,2107],{"class":756,"line":863},[754,2108,800],{"emptyLinePlaceholder":422},[754,2110,2111],{"class":756,"line":868},[754,2112,2113],{},"# 開發依賴\n",[754,2115,2116],{"class":756,"line":874},[754,2117,2118],{},"[project.optional-dependencies]\n",[754,2120,2121],{"class":756,"line":880},[754,2122,2123],{},"dev = [\n",[754,2125,2126],{"class":756,"line":886},[754,2127,2128],{},"    \"pytest>=7.0.0\",\n",[754,2130,2131],{"class":756,"line":892},[754,2132,2133],{},"    \"ruff>=0.1.0\",\n",[754,2135,2136],{"class":756,"line":898},[754,2137,2138],{},"    \"mypy>=1.0.0\",\n",[754,2140,2141],{"class":756,"line":903},[754,2142,2076],{},[754,2144,2145],{"class":756,"line":909},[754,2146,2147],{},"test = [\n",[754,2149,2150],{"class":756,"line":915},[754,2151,2152],{},"    \"pytest-cov>=4.0.0\",\n",[754,2154,2155],{"class":756,"line":921},[754,2156,2157],{},"    \"pytest-mock>=3.10.0\",\n",[754,2159,2160],{"class":756,"line":926},[754,2161,2076],{},[754,2163,2164],{"class":756,"line":932},[754,2165,800],{"emptyLinePlaceholder":422},[754,2167,2168],{"class":756,"line":938},[754,2169,2170],{},"# 工具配置\n",[754,2172,2173],{"class":756,"line":944},[754,2174,2175],{},"[tool.ruff]\n",[754,2177,2178],{"class":756,"line":950},[754,2179,2180],{},"line-length = 88\n",[754,2182,2183],{"class":756,"line":955},[754,2184,2185],{},"target-version = \"py311\"\n",[754,2187,2188],{"class":756,"line":961},[754,2189,800],{"emptyLinePlaceholder":422},[754,2191,2192],{"class":756,"line":967},[754,2193,2194],{},"[tool.ruff.lint]\n",[754,2196,2197],{"class":756,"line":973},[754,2198,2199],{},"select = [\"E\", \"F\", \"UP\", \"B\", \"SIM\", \"I\"]\n",[754,2201,2202],{"class":756,"line":979},[754,2203,800],{"emptyLinePlaceholder":422},[754,2205,2206],{"class":756,"line":985},[754,2207,2208],{},"[tool.pytest.ini_options]\n",[754,2210,2211],{"class":756,"line":991},[754,2212,2213],{},"testpaths = [\"tests\"]\n",[754,2215,2216],{"class":756,"line":997},[754,2217,2218],{},"python_files = [\"test_*.py\"]\n",[754,2220,2221],{"class":756,"line":1003},[754,2222,800],{"emptyLinePlaceholder":422},[754,2224,2225],{"class":756,"line":1009},[754,2226,2227],{},"[build-system]\n",[754,2229,2230],{"class":756,"line":1015},[754,2231,2232],{},"requires = [\"setuptools>=61.0\"]\n",[754,2234,2235],{"class":756,"line":1021},[754,2236,2237],{},"build-backend = \"setuptools.build_meta\"\n",[61,2239,2240],{"id":2240},"專案檔案架構比較",[19,2242,2243],{},[32,2244,2245],{},"使用 requirements.txt 的專案結構",[745,2247,2252],{"className":2248,"code":2250,"language":2251},[2249],"language-text","my-project/\n├── requirements.txt\n├── requirements-dev.txt\n├── requirements-test.txt\n├── setup.py        # setuptools 配置\n├── setup.cfg\n├── pytest.ini      # pytest 配置\n├── mypy.ini        # mypy 配置\n├── .coveragerc     # coverage 配置\n└── pyproject.toml  # 只給 ruff 用\n","text",[751,2253,2250],{"__ignoreMap":402},[19,2255,2256],{},[32,2257,2258],{},"使用 pyproject.toml 的專案結構",[745,2260,2263],{"className":2261,"code":2262,"language":2251},[2249],"my-project/\n├── pyproject.toml  # 所有配置都在這裡\n├── uv.lock         # 版本鎖定檔案\n└── src/\n",[751,2264,2262],{"__ignoreMap":402},[2266,2267],"hr",{},[1903,2269,2270],{"id":2270},"ruff",[16,2272,2273,2276],{},[19,2274,2275],{},"ruff 是一個極速的 Python linter 和 code formatter，用 Rust 編寫，可以替代 Flake8、isort、Black 等多個工具。",[19,2277,2278],{},"它的目標是提供最快速、最全面的 Python 程式碼品質檢查和格式化解決方案。",[11,2280,2282],{"id":2281},"ruff-的主要特點","ruff 的主要特點",[26,2284,2285,2287,2300],{},[29,2286,1931],{},[29,2288,2289,2292],{},[32,2290,2291],{},"豐富的規則集",[26,2293,2294,2297],{},[29,2295,2296],{},"支援 800+ 個 lint 規則",[29,2298,2299],{},"整合了 Flake8、isort、pycodestyle、pyflakes 等工具的規則",[29,2301,2302],{},[32,2303,2304],{},"無需配置即可使用",[2266,2306],{},[1903,2308,2310],{"id":2309},"為什麼要使用-uv-和-ruff","為什麼要使用 uv 和 ruff？",[26,2312,2313,2329,2335,2352],{},[29,2314,2315,2318,2319],{},[32,2316,2317],{},"即時程式碼檢查","：ruff 的極速檢查讓程式碼品質控制變得無縫\n",[26,2320,2321],{},[29,2322,2323,2324],{},"尤其公司專案目前很多軟體動輒幾千行（較少抽象與依功能分割檔案），使用傳統程式碼檢查與 format 工具需要接近 1 分鐘或甚至更多\n",[26,2325,2326],{},[29,2327,2328],{},"想像你每次 Ctrl + S 都要等 1 分鐘…",[29,2330,2331,2334],{},[32,2332,2333],{},"穩定的工具鏈","：目前 uv 與 ruff 算是在各自領域（套件管理與 lint check / format）統一江湖的存在，未來不太會遇到需要再更換的情況",[29,2336,2337,2338],{},"為了未來可能需要統一產品版本鋪路，使用 Git 協作的情況會越來越多\n",[26,2339,2340,2346],{},[29,2341,2342,2345],{},[32,2343,2344],{},"一致的環境","：uv 確保所有團隊成員使用相同的依賴版本",[29,2347,2348,2351],{},[32,2349,2350],{},"統一的程式碼風格","：ruff 自動化程式碼風格檢查和格式化",[29,2353,2354,2357],{},[32,2355,2356],{},"更快的 CI/CD","：極速的執行效能減少構建時間，現在也有使用 GKE 的專案，可以減少 runner 開銷",[2266,2359],{},[1903,2361,2362],{"id":2362},"遷移範例",[19,2364,2365],{},"假設原本使用 requirements.txt + 很多 lint error",[26,2367,2368],{},[29,2369,2370,2371],{},"lint error 例如：\n",[26,2372,2373,2378,2381,2384],{},[29,2374,2375],{},[751,2376,2377],{},"if a == None",[29,2379,2380],{},"assign var or import but never used",[29,2382,2383],{},"assign a python keyword as a var name",[29,2385,2386,2387,2390],{},"use ",[751,2388,2389],{},"format"," instead of f-string",[19,2392,2393],{},"有遇到任何問題找 AI 處理，或是看文檔的 best practices",[11,2395,2397],{"id":2396},"_1-安裝與驗證","1. 安裝與驗證",[745,2399,2401],{"className":1447,"code":2400,"language":1449,"meta":402,"style":402},"# 安裝 uv\npip install uv\n\n# 驗證（否則要看一下文檔，根據作業系統有不同安裝方式）\nuv --version\n",[751,2402,2403,2409,2420,2424,2429],{"__ignoreMap":402},[754,2404,2405],{"class":756,"line":757},[754,2406,2408],{"class":2407},"sJ8bj","# 安裝 uv\n",[754,2410,2411,2414,2417],{"class":756,"line":403},[754,2412,2413],{"class":1456},"pip",[754,2415,2416],{"class":1460}," install",[754,2418,2419],{"class":1460}," uv\n",[754,2421,2422],{"class":756,"line":409},[754,2423,800],{"emptyLinePlaceholder":422},[754,2425,2426],{"class":756,"line":773},[754,2427,2428],{"class":2407},"# 驗證（否則要看一下文檔，根據作業系統有不同安裝方式）\n",[754,2430,2431,2433],{"class":756,"line":779},[754,2432,1912],{"class":1456},[754,2434,2435],{"class":1467}," --version\n",[11,2437,2439],{"id":2438},"_2-init-專案與安裝依賴","2. init 專案與安裝依賴",[745,2441,2443],{"className":1447,"code":2442,"language":1449,"meta":402,"style":402},"# 移到專案根目錄\ncd {your_project}\n\n# init 專案\nuv init --no-readme\n\n# 從現有 requirements.txt 遷移\nuv add -r requirements.txt\n\n# 手動新增依賴 (if needed)\nuv add requests numpy\n\n# 安裝 ruff\nuv add --dev ruff\n",[751,2444,2445,2450,2458,2462,2467,2477,2481,2486,2499,2503,2508,2520,2524,2529],{"__ignoreMap":402},[754,2446,2447],{"class":756,"line":757},[754,2448,2449],{"class":2407},"# 移到專案根目錄\n",[754,2451,2452,2455],{"class":756,"line":403},[754,2453,2454],{"class":1467},"cd",[754,2456,2457],{"class":1460}," {your_project}\n",[754,2459,2460],{"class":756,"line":409},[754,2461,800],{"emptyLinePlaceholder":422},[754,2463,2464],{"class":756,"line":773},[754,2465,2466],{"class":2407},"# init 專案\n",[754,2468,2469,2471,2474],{"class":756,"line":779},[754,2470,1912],{"class":1456},[754,2472,2473],{"class":1460}," init",[754,2475,2476],{"class":1467}," --no-readme\n",[754,2478,2479],{"class":756,"line":785},[754,2480,800],{"emptyLinePlaceholder":422},[754,2482,2483],{"class":756,"line":791},[754,2484,2485],{"class":2407},"# 從現有 requirements.txt 遷移\n",[754,2487,2488,2490,2493,2496],{"class":756,"line":797},[754,2489,1912],{"class":1456},[754,2491,2492],{"class":1460}," add",[754,2494,2495],{"class":1467}," -r",[754,2497,2498],{"class":1460}," requirements.txt\n",[754,2500,2501],{"class":756,"line":803},[754,2502,800],{"emptyLinePlaceholder":422},[754,2504,2505],{"class":756,"line":809},[754,2506,2507],{"class":2407},"# 手動新增依賴 (if needed)\n",[754,2509,2510,2512,2514,2517],{"class":756,"line":815},[754,2511,1912],{"class":1456},[754,2513,2492],{"class":1460},[754,2515,2516],{"class":1460}," requests",[754,2518,2519],{"class":1460}," numpy\n",[754,2521,2522],{"class":756,"line":821},[754,2523,800],{"emptyLinePlaceholder":422},[754,2525,2526],{"class":756,"line":827},[754,2527,2528],{"class":2407},"# 安裝 ruff\n",[754,2530,2531,2533,2535,2538],{"class":756,"line":833},[754,2532,1912],{"class":1456},[754,2534,2492],{"class":1460},[754,2536,2537],{"class":1467}," --dev",[754,2539,2540],{"class":1460}," ruff\n",[11,2542,2544],{"id":2543},"_3-設定-python-版本","3. 設定 python 版本",[745,2546,2548],{"className":1447,"code":2547,"language":1449,"meta":402,"style":402},"# 查看可用的 Python 版本\nuv python list\n\n# 範例輸出：\n# cpython-3.14.0b4-macos-aarch64-none                 \u003Cdownload available>\n# cpython-3.14.0b4+freethreaded-macos-aarch64-none    \u003Cdownload available>\n# cpython-3.13.5-macos-aarch64-none                   /opt/homebrew/bin/python3.13\n# cpython-3.13.5-macos-aarch64-none                   /opt/homebrew/bin/python3\n# cpython-3.13.5-macos-aarch64-none                   \u003Cdownload available>\n\n# 設定專案使用的 Python 版本（例如 3.10）\nuv python pin 3.10\n",[751,2549,2550,2555,2565,2569,2574,2579,2584,2589,2594,2599,2603,2608],{"__ignoreMap":402},[754,2551,2552],{"class":756,"line":757},[754,2553,2554],{"class":2407},"# 查看可用的 Python 版本\n",[754,2556,2557,2559,2562],{"class":756,"line":403},[754,2558,1912],{"class":1456},[754,2560,2561],{"class":1460}," python",[754,2563,2564],{"class":1460}," list\n",[754,2566,2567],{"class":756,"line":409},[754,2568,800],{"emptyLinePlaceholder":422},[754,2570,2571],{"class":756,"line":773},[754,2572,2573],{"class":2407},"# 範例輸出：\n",[754,2575,2576],{"class":756,"line":779},[754,2577,2578],{"class":2407},"# cpython-3.14.0b4-macos-aarch64-none                 \u003Cdownload available>\n",[754,2580,2581],{"class":756,"line":785},[754,2582,2583],{"class":2407},"# cpython-3.14.0b4+freethreaded-macos-aarch64-none    \u003Cdownload available>\n",[754,2585,2586],{"class":756,"line":791},[754,2587,2588],{"class":2407},"# cpython-3.13.5-macos-aarch64-none                   /opt/homebrew/bin/python3.13\n",[754,2590,2591],{"class":756,"line":797},[754,2592,2593],{"class":2407},"# cpython-3.13.5-macos-aarch64-none                   /opt/homebrew/bin/python3\n",[754,2595,2596],{"class":756,"line":803},[754,2597,2598],{"class":2407},"# cpython-3.13.5-macos-aarch64-none                   \u003Cdownload available>\n",[754,2600,2601],{"class":756,"line":809},[754,2602,800],{"emptyLinePlaceholder":422},[754,2604,2605],{"class":756,"line":815},[754,2606,2607],{"class":2407},"# 設定專案使用的 Python 版本（例如 3.10）\n",[754,2609,2610,2612,2614,2617],{"class":756,"line":821},[754,2611,1912],{"class":1456},[754,2613,2561],{"class":1460},[754,2615,2616],{"class":1460}," pin",[754,2618,2619],{"class":1467}," 3.10\n",[11,2621,2623,2624],{"id":2622},"_4-設定-pyprojecttoml","4. 設定 ",[751,2625,2626],{},"pyproject.toml",[19,2628,2629,2630,2633],{},"下面只是範例，基本上只需要注意 ",[751,2631,2632],{},"tool.ruff"," 相關的部分",[745,2635,2637],{"className":2012,"code":2636,"language":2014,"meta":402,"style":402},"[project]\nname = \"my-project\"\nversion = \"0.1.0\"\ndescription = \"Add your description here\"\ndependencies = [\n    \"numpy>=1.24.0\",\n    \"requests>=2.31.0\",\n]\n\n[tool.uv]\ndev-dependencies = [\n    \"black>=23.7.0\",\n    \"flake8>=6.0.0\",\n    \"pytest>=7.4.0\",\n    \"ruff>=0.1.6\",\n]\n\n[build-system]\nrequires = [\"hatchling\"]\nbuild-backend = \"hatchling.build\"\n\n# 加上 ruff 相關設置\n[tool.ruff]\nline-length = 88\ntarget-version = \"py310\"  # 改成你的 python 版本\n\n[tool.ruff.lint]\nselect = [\n    \"E\",   # pycodestyle errors\n    \"W\",   # pycodestyle warnings\n    \"F\",   # pyflakes\n    \"I\",   # isort\n    \"C\",   # flake8-comprehensions\n    \"B\",   # flake8-bugbear\n    \"UP\",  # pyupgrade\n]\nignore = [\n    \"E501\",  # line too long, handled by black\n    \"B008\",  # do not perform function calls in argument defaults\n    \"C901\",  # too complex\n    \"W191\",  # indentation contains tabs\n]\nexclude = [\n    \"tests/*\",\n    \"venv/*\",\n    \"*/site-packages/*\",\n    \"*/static/*\",\n    \"wsgi.py\",\n]\nfixable = [\"ALL\"]\nunfixable = []\n\n[tool.ruff.lint.per-file-ignores]\n\"tests/**/*\" = [\"S101\"]  # 測試中允許 assert\n\n[tool.ruff.format]\nquote-style = \"double\"\nindent-style = \"space\"\n",[751,2638,2639,2643,2648,2653,2658,2662,2667,2672,2676,2680,2685,2690,2695,2700,2705,2710,2714,2718,2722,2727,2732,2736,2741,2745,2749,2754,2758,2762,2767,2772,2777,2782,2787,2792,2797,2802,2806,2811,2816,2821,2826,2831,2835,2840,2845,2850,2855,2860,2865,2869,2874,2879,2883,2888,2893,2897,2902,2907],{"__ignoreMap":402},[754,2640,2641],{"class":756,"line":757},[754,2642,2021],{},[754,2644,2645],{"class":756,"line":403},[754,2646,2647],{},"name = \"my-project\"\n",[754,2649,2650],{"class":756,"line":409},[754,2651,2652],{},"version = \"0.1.0\"\n",[754,2654,2655],{"class":756,"line":773},[754,2656,2657],{},"description = \"Add your description here\"\n",[754,2659,2660],{"class":756,"line":779},[754,2661,2090],{},[754,2663,2664],{"class":756,"line":785},[754,2665,2666],{},"    \"numpy>=1.24.0\",\n",[754,2668,2669],{"class":756,"line":791},[754,2670,2671],{},"    \"requests>=2.31.0\",\n",[754,2673,2674],{"class":756,"line":797},[754,2675,2076],{},[754,2677,2678],{"class":756,"line":803},[754,2679,800],{"emptyLinePlaceholder":422},[754,2681,2682],{"class":756,"line":809},[754,2683,2684],{},"[tool.uv]\n",[754,2686,2687],{"class":756,"line":815},[754,2688,2689],{},"dev-dependencies = [\n",[754,2691,2692],{"class":756,"line":821},[754,2693,2694],{},"    \"black>=23.7.0\",\n",[754,2696,2697],{"class":756,"line":827},[754,2698,2699],{},"    \"flake8>=6.0.0\",\n",[754,2701,2702],{"class":756,"line":833},[754,2703,2704],{},"    \"pytest>=7.4.0\",\n",[754,2706,2707],{"class":756,"line":839},[754,2708,2709],{},"    \"ruff>=0.1.6\",\n",[754,2711,2712],{"class":756,"line":845},[754,2713,2076],{},[754,2715,2716],{"class":756,"line":851},[754,2717,800],{"emptyLinePlaceholder":422},[754,2719,2720],{"class":756,"line":857},[754,2721,2227],{},[754,2723,2724],{"class":756,"line":863},[754,2725,2726],{},"requires = [\"hatchling\"]\n",[754,2728,2729],{"class":756,"line":868},[754,2730,2731],{},"build-backend = \"hatchling.build\"\n",[754,2733,2734],{"class":756,"line":874},[754,2735,800],{"emptyLinePlaceholder":422},[754,2737,2738],{"class":756,"line":880},[754,2739,2740],{},"# 加上 ruff 相關設置\n",[754,2742,2743],{"class":756,"line":886},[754,2744,2175],{},[754,2746,2747],{"class":756,"line":892},[754,2748,2180],{},[754,2750,2751],{"class":756,"line":898},[754,2752,2753],{},"target-version = \"py310\"  # 改成你的 python 版本\n",[754,2755,2756],{"class":756,"line":903},[754,2757,800],{"emptyLinePlaceholder":422},[754,2759,2760],{"class":756,"line":909},[754,2761,2194],{},[754,2763,2764],{"class":756,"line":915},[754,2765,2766],{},"select = [\n",[754,2768,2769],{"class":756,"line":921},[754,2770,2771],{},"    \"E\",   # pycodestyle errors\n",[754,2773,2774],{"class":756,"line":926},[754,2775,2776],{},"    \"W\",   # pycodestyle warnings\n",[754,2778,2779],{"class":756,"line":932},[754,2780,2781],{},"    \"F\",   # pyflakes\n",[754,2783,2784],{"class":756,"line":938},[754,2785,2786],{},"    \"I\",   # isort\n",[754,2788,2789],{"class":756,"line":944},[754,2790,2791],{},"    \"C\",   # flake8-comprehensions\n",[754,2793,2794],{"class":756,"line":950},[754,2795,2796],{},"    \"B\",   # flake8-bugbear\n",[754,2798,2799],{"class":756,"line":955},[754,2800,2801],{},"    \"UP\",  # pyupgrade\n",[754,2803,2804],{"class":756,"line":961},[754,2805,2076],{},[754,2807,2808],{"class":756,"line":967},[754,2809,2810],{},"ignore = [\n",[754,2812,2813],{"class":756,"line":973},[754,2814,2815],{},"    \"E501\",  # line too long, handled by black\n",[754,2817,2818],{"class":756,"line":979},[754,2819,2820],{},"    \"B008\",  # do not perform function calls in argument defaults\n",[754,2822,2823],{"class":756,"line":985},[754,2824,2825],{},"    \"C901\",  # too complex\n",[754,2827,2828],{"class":756,"line":991},[754,2829,2830],{},"    \"W191\",  # indentation contains tabs\n",[754,2832,2833],{"class":756,"line":997},[754,2834,2076],{},[754,2836,2837],{"class":756,"line":1003},[754,2838,2839],{},"exclude = [\n",[754,2841,2842],{"class":756,"line":1009},[754,2843,2844],{},"    \"tests/*\",\n",[754,2846,2847],{"class":756,"line":1015},[754,2848,2849],{},"    \"venv/*\",\n",[754,2851,2852],{"class":756,"line":1021},[754,2853,2854],{},"    \"*/site-packages/*\",\n",[754,2856,2857],{"class":756,"line":1027},[754,2858,2859],{},"    \"*/static/*\",\n",[754,2861,2862],{"class":756,"line":1032},[754,2863,2864],{},"    \"wsgi.py\",\n",[754,2866,2867],{"class":756,"line":1038},[754,2868,2076],{},[754,2870,2871],{"class":756,"line":1043},[754,2872,2873],{},"fixable = [\"ALL\"]\n",[754,2875,2876],{"class":756,"line":1048},[754,2877,2878],{},"unfixable = []\n",[754,2880,2881],{"class":756,"line":1053},[754,2882,800],{"emptyLinePlaceholder":422},[754,2884,2885],{"class":756,"line":1058},[754,2886,2887],{},"[tool.ruff.lint.per-file-ignores]\n",[754,2889,2890],{"class":756,"line":1063},[754,2891,2892],{},"\"tests/**/*\" = [\"S101\"]  # 測試中允許 assert\n",[754,2894,2895],{"class":756,"line":1069},[754,2896,800],{"emptyLinePlaceholder":422},[754,2898,2899],{"class":756,"line":1074},[754,2900,2901],{},"[tool.ruff.format]\n",[754,2903,2904],{"class":756,"line":1080},[754,2905,2906],{},"quote-style = \"double\"\n",[754,2908,2909],{"class":756,"line":1086},[754,2910,2911],{},"indent-style = \"space\"\n",[11,2913,2915],{"id":2914},"_5-安裝依賴","5. 安裝依賴",[745,2917,2919],{"className":1447,"code":2918,"language":1449,"meta":402,"style":402},"# 這會產生 uv.lock，第一次加上 --frozen 就好\nuv sync --frozen\n",[751,2920,2921,2926],{"__ignoreMap":402},[754,2922,2923],{"class":756,"line":757},[754,2924,2925],{"class":2407},"# 這會產生 uv.lock，第一次加上 --frozen 就好\n",[754,2927,2928,2930,2933],{"class":756,"line":403},[754,2929,1912],{"class":1456},[754,2931,2932],{"class":1460}," sync",[754,2934,2935],{"class":1467}," --frozen\n",[11,2937,2939],{"id":2938},"_6-ide-設置如果你使用-vs-code","6. IDE 設置（如果你使用 VS Code）",[93,2941,2942,2945,2948],{},[29,2943,2944],{},"安裝 VS Code extensions（如果你使用 VS Code，可以去找一下 ruff 的 extension，可以使用 IDE 的修復輔助）",[29,2946,2947],{},"Ctrl + Shift + P：>Format Document With… 將 ruff 設為 default formatter",[29,2949,2950],{},"確保 format on save = true",[11,2952,2954],{"id":2953},"_7-清理現有代碼","7. 清理現有代碼",[745,2956,2958],{"className":1447,"code":2957,"language":1449,"meta":402,"style":402},"# 先看有幾個錯誤，以及可以使用 --fix 自動修復的項目\nruff check\n\n# 自動修復\nruff check --fix\n\n# 接下來開始清理 code style 問題\n# 啟用 hot reload，可以快速修復已存在的錯誤\nruff check --watch\n",[751,2959,2960,2965,2972,2976,2981,2991,2995,3000,3005],{"__ignoreMap":402},[754,2961,2962],{"class":756,"line":757},[754,2963,2964],{"class":2407},"# 先看有幾個錯誤，以及可以使用 --fix 自動修復的項目\n",[754,2966,2967,2969],{"class":756,"line":403},[754,2968,2270],{"class":1456},[754,2970,2971],{"class":1460}," check\n",[754,2973,2974],{"class":756,"line":409},[754,2975,800],{"emptyLinePlaceholder":422},[754,2977,2978],{"class":756,"line":773},[754,2979,2980],{"class":2407},"# 自動修復\n",[754,2982,2983,2985,2988],{"class":756,"line":779},[754,2984,2270],{"class":1456},[754,2986,2987],{"class":1460}," check",[754,2989,2990],{"class":1467}," --fix\n",[754,2992,2993],{"class":756,"line":785},[754,2994,800],{"emptyLinePlaceholder":422},[754,2996,2997],{"class":756,"line":791},[754,2998,2999],{"class":2407},"# 接下來開始清理 code style 問題\n",[754,3001,3002],{"class":756,"line":797},[754,3003,3004],{"class":2407},"# 啟用 hot reload，可以快速修復已存在的錯誤\n",[754,3006,3007,3009,3011],{"class":756,"line":803},[754,3008,2270],{"class":1456},[754,3010,2987],{"class":1460},[754,3012,3013],{"class":1467}," --watch\n",[11,3015,3017],{"id":3016},"_8-執行專案","8. 執行專案",[745,3019,3021],{"className":1447,"code":3020,"language":1449,"meta":402,"style":402},"uv run pytest\nuv run python src/main.py\n",[751,3022,3023,3032],{"__ignoreMap":402},[754,3024,3025,3027,3029],{"class":756,"line":757},[754,3026,1912],{"class":1456},[754,3028,1464],{"class":1460},[754,3030,3031],{"class":1460}," pytest\n",[754,3033,3034,3036,3038,3040],{"class":756,"line":403},[754,3035,1912],{"class":1456},[754,3037,1464],{"class":1460},[754,3039,2561],{"class":1460},[754,3041,3042],{"class":1460}," src/main.py\n",[11,3044,3046],{"id":3045},"_9-dockerfile-範例","9. Dockerfile 範例",[745,3048,3052],{"className":3049,"code":3050,"language":3051,"meta":402,"style":402},"language-dockerfile shiki shiki-themes github-light github-dark","# 使用官方 Python 基礎映像\nFROM python:3.11-slim\n\n# 設定工作目錄\nWORKDIR /app\n\n# 安裝 uv\nCOPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /usr/local/bin/\n\n# 複製依賴文件\nCOPY pyproject.toml uv.lock ./\n\n# 安裝依賴（不包含開發依賴）\nRUN uv sync --frozen --no-dev\n\n# 複製應用程式代碼\nCOPY . .\n\n# 設定 Python 路徑\nENV PATH=\"/app/.venv/bin:$PATH\"\n\n# 暴露端口（根據你的應用程式調整）\nEXPOSE 8000\n\n# 執行應用程式\nCMD [\"python\", \"src/main.py\"]\n","dockerfile",[751,3053,3054,3059,3064,3068,3073,3078,3082,3086,3091,3095,3100,3105,3109,3114,3119,3123,3128,3133,3137,3142,3147,3151,3156,3161,3165,3170],{"__ignoreMap":402},[754,3055,3056],{"class":756,"line":757},[754,3057,3058],{},"# 使用官方 Python 基礎映像\n",[754,3060,3061],{"class":756,"line":403},[754,3062,3063],{},"FROM python:3.11-slim\n",[754,3065,3066],{"class":756,"line":409},[754,3067,800],{"emptyLinePlaceholder":422},[754,3069,3070],{"class":756,"line":773},[754,3071,3072],{},"# 設定工作目錄\n",[754,3074,3075],{"class":756,"line":779},[754,3076,3077],{},"WORKDIR /app\n",[754,3079,3080],{"class":756,"line":785},[754,3081,800],{"emptyLinePlaceholder":422},[754,3083,3084],{"class":756,"line":791},[754,3085,2408],{},[754,3087,3088],{"class":756,"line":797},[754,3089,3090],{},"COPY --from=ghcr.io/astral-sh/uv:latest /uv /uvx /usr/local/bin/\n",[754,3092,3093],{"class":756,"line":803},[754,3094,800],{"emptyLinePlaceholder":422},[754,3096,3097],{"class":756,"line":809},[754,3098,3099],{},"# 複製依賴文件\n",[754,3101,3102],{"class":756,"line":815},[754,3103,3104],{},"COPY pyproject.toml uv.lock ./\n",[754,3106,3107],{"class":756,"line":821},[754,3108,800],{"emptyLinePlaceholder":422},[754,3110,3111],{"class":756,"line":827},[754,3112,3113],{},"# 安裝依賴（不包含開發依賴）\n",[754,3115,3116],{"class":756,"line":833},[754,3117,3118],{},"RUN uv sync --frozen --no-dev\n",[754,3120,3121],{"class":756,"line":839},[754,3122,800],{"emptyLinePlaceholder":422},[754,3124,3125],{"class":756,"line":845},[754,3126,3127],{},"# 複製應用程式代碼\n",[754,3129,3130],{"class":756,"line":851},[754,3131,3132],{},"COPY . .\n",[754,3134,3135],{"class":756,"line":857},[754,3136,800],{"emptyLinePlaceholder":422},[754,3138,3139],{"class":756,"line":863},[754,3140,3141],{},"# 設定 Python 路徑\n",[754,3143,3144],{"class":756,"line":868},[754,3145,3146],{},"ENV PATH=\"/app/.venv/bin:$PATH\"\n",[754,3148,3149],{"class":756,"line":874},[754,3150,800],{"emptyLinePlaceholder":422},[754,3152,3153],{"class":756,"line":880},[754,3154,3155],{},"# 暴露端口（根據你的應用程式調整）\n",[754,3157,3158],{"class":756,"line":886},[754,3159,3160],{},"EXPOSE 8000\n",[754,3162,3163],{"class":756,"line":892},[754,3164,800],{"emptyLinePlaceholder":422},[754,3166,3167],{"class":756,"line":898},[754,3168,3169],{},"# 執行應用程式\n",[754,3171,3172],{"class":756,"line":903},[754,3173,3174],{},"CMD [\"python\", \"src/main.py\"]\n",[2266,3176],{},[1903,3178,368],{"id":368},[26,3180,3181,3188,3195],{},[29,3182,3183],{},[374,3184,3187],{"href":3185,"rel":3186},"https://astral.sh/",[378],"Astral: High-performance Python tooling",[29,3189,3190],{},[374,3191,3194],{"href":3192,"rel":3193},"https://docs.astral.sh/uv/",[378],"uv Documentation",[29,3196,3197],{},[374,3198,3201],{"href":3199,"rel":3200},"https://docs.astral.sh/ruff/",[378],"Ruff Documentation",[1866,3203,3204],{},"html .default .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .shiki span {color: var(--shiki-default);background: var(--shiki-default-bg);font-style: var(--shiki-default-font-style);font-weight: var(--shiki-default-font-weight);text-decoration: var(--shiki-default-text-decoration);}html .dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html.dark .shiki span {color: var(--shiki-dark);background: var(--shiki-dark-bg);font-style: var(--shiki-dark-font-style);font-weight: var(--shiki-dark-font-weight);text-decoration: var(--shiki-dark-text-decoration);}html pre.shiki code .sJ8bj, html code.shiki .sJ8bj{--shiki-default:#6A737D;--shiki-dark:#6A737D}html pre.shiki code .sScJk, html code.shiki .sScJk{--shiki-default:#6F42C1;--shiki-dark:#B392F0}html pre.shiki code .sZZnC, html code.shiki .sZZnC{--shiki-default:#032F62;--shiki-dark:#9ECBFF}html pre.shiki code .sj4cs, html code.shiki .sj4cs{--shiki-default:#005CC5;--shiki-dark:#79B8FF}",{"title":402,"searchDepth":403,"depth":403,"links":3206},[3207,3208,3212,3213,3214,3215,3216,3218,3219,3220,3221,3222],{"id":1923,"depth":403,"text":1924},{"id":1957,"depth":403,"text":1958,"children":3209},[3210,3211],{"id":2008,"depth":409,"text":2009},{"id":2240,"depth":409,"text":2240},{"id":2281,"depth":403,"text":2282},{"id":2396,"depth":403,"text":2397},{"id":2438,"depth":403,"text":2439},{"id":2543,"depth":403,"text":2544},{"id":2622,"depth":403,"text":3217},"4. 設定 pyproject.toml",{"id":2914,"depth":403,"text":2915},{"id":2938,"depth":403,"text":2939},{"id":2953,"depth":403,"text":2954},{"id":3016,"depth":403,"text":3017},{"id":3045,"depth":403,"text":3046},"介紹 uv 和 Ruff，兩個最佳的 Python 工具鏈，以及如何遷移到 uv 和 Ruff。",{},"/blog/uv-and-ruff",{"title":1899,"description":3223},"blog/uv-and-ruff",[427,3229,3230,1912,3231],"Tooling","Development","Ruff","-zRvt4hekmdP0cJ82m1OICrMfHIMFKCtweqM3DQ743s",{"id":3234,"title":3235,"author":6,"body":3236,"category":416,"date":3560,"description":3561,"draft":419,"extension":420,"image":3562,"meta":3563,"navigation":422,"path":3564,"seo":3565,"stem":3566,"tags":3567,"__hash__":3575},"blog/blog/20260304-troublemaker.md","關於我一天在公司 AWS 開發帳號花掉 14000 鎂的那回事",{"type":8,"value":3237,"toc":3542},[3238,3245,3248,3252,3259,3262,3271,3280,3287,3290,3304,3307,3312,3315,3318,3325,3328,3331,3334,3338,3341,3345,3348,3353,3362,3374,3377,3385,3390,3393,3396,3401,3404,3411,3416,3420,3423,3434,3438,3441,3448,3455,3458,3461,3464,3467,3470,3473,3476,3479,3483,3486,3489,3495,3499,3502,3513,3517,3520,3527,3530,3533,3536,3539],[19,3239,3240,3241,3244],{},"身為工程師，你可能聽過同事不小心把 Production 資料庫砍了、或是忘記關 EC2 多燒了幾百塊。但你有聽過",[32,3242,3243],{},"用雲服務一天燒掉 14,000 美金","的嗎？",[19,3246,3247],{},"沒錯，這件事發生在我身上...嗎？",[11,3249,3251],{"id":3250},"tldr","TL;DR",[19,3253,3254,3255,3258],{},"在公司開發帳號 survey AWS Bedrock AgentCore Policy 功能，試用了 Cedar Policy Generator。幾天後帳單突然出現一筆 ",[32,3256,3257],{},"$14,000+ USD 的單日費用","。經過 CloudTrail 排查確認是 Cedar Generator 觸發的異常計費，最終 AWS 承認是 Bedrock 端的計費 bug，修復並校正了帳單。",[11,3260,3261],{"id":3261},"事發經過",[19,3263,3264,3265,3270],{},"3/4 我因為看到 ",[374,3266,3269],{"href":3267,"rel":3268},"https://aws.amazon.com/bedrock/agentcore/",[378],"AgentCore"," 新 Feature - Policy 剛上線，所以需要 Survey 一下。",[19,3272,3273,3274,3279],{},"AgentCore Policy 讓你可以用 ",[374,3275,3278],{"href":3276,"rel":3277},"https://www.cedarpolicy.com/",[378],"Cedar"," 語言來定義 Agent 的授權策略，控制 Agent 能存取哪些工具和資源。Cedar 是 AWS 開源的授權語言，語法可讀性很高，設計上是要讓非工程師也能看得懂的那種。",[19,3281,3282,3283,3286],{},"而 AgentCore 很貼心地提供了一個 ",[32,3284,3285],{},"Natural Language Policy Generator","——你用自然語言描述你要的權限規則，它就幫你生成對應的 Cedar Policy。聽起來很 User-friendly 對吧？",[19,3288,3289],{},"我就照著文件走了一遍流程：",[93,3291,3292,3295,3298,3301],{},[29,3293,3294],{},"建了一個 Policy Engine",[29,3296,3297],{},"試了幾次 Cedar Policy Generator（用自然語言描述轉成 Cedar）",[29,3299,3300],{},"確認功能可以正常運作",[29,3302,3303],{},"收工，覺得這功能還不錯",[19,3305,3306],{},"整個過程大概就一兩個小時，正常的 survey 流程。",[19,3308,3309],{},[32,3310,3311],{},"然後就沒有然後了——直到五天後。",[11,3313,3314],{"id":3314},"帳單爆炸",[19,3316,3317],{},"後來請假看完中華隊在 WBC 的比賽，打贏韓國那場實在很感動，回來上班的第一天，3/9 下午，Slack突然被狂 tag，我被我們公司的 Billing Manager & Team Lead 問為何會有一筆費用產生，我也趕緊地打開CE，一個讓我愣住的數字：",[16,3319,3320],{},[19,3321,3322],{},[32,3323,3324],{},"3/4 單日Agentcore產生了 $14,000+ USD的費用",[19,3326,3327],{},"我先是以為自己眼花了。重新整理頁面，數字還在那裡。",[19,3329,3330],{},"完了... 哪裡搞錯了吧？",[11,3332,3333],{"id":3333},"排查過程",[61,3335,3337],{"id":3336},"step-1先開-support-ticket","Step 1：先開 Support Ticket",[19,3339,3340],{},"不管三七二十一，先開 AWS Support Ticket 回報異常帳單。把時間範圍、帳號資訊、異常金額都附上去，讓 Support 那邊開始調查。",[61,3342,3344],{"id":3343},"step-2自己也同步排查","Step 2：自己也同步排查",[19,3346,3347],{},"等 Support 回覆的同時，我也開始自己排查紀錄。",[19,3349,3350],{},[32,3351,3352],{},"確認 AgentCore Policy 的收費機制",[19,3354,3355,3356,3361],{},"根據 ",[374,3357,3360],{"href":3358,"rel":3359},"https://aws.amazon.com/bedrock/agentcore/pricing/",[378],"AgentCore 定價頁面","，Policy 的計費主要是：",[26,3363,3364,3371],{},[29,3365,3366,3367,3370],{},"Cedar Policy Generator：",[32,3368,3369],{},"按 input token 數量計費","（每 1,000 tokens）",[29,3372,3373],{},"Policy Engine 的 Authorization 請求：按請求數計費",[19,3375,3376],{},"稍微思考一下：",[93,3378,3379,3382],{},[29,3380,3381],{},"我當天的使用量根本不可能撐到這個金額。就算我瘋狂打 Generator 也打不出 $14,000，同事跟我說 Billing 那邊顯示 Policy 使用了 109 1M Tokens (接近 1.1 億，我甚至不知道一天要怎麼用掉那麼多 Tokens...)。",[29,3383,3384],{},"我的 Policy Engine 並沒有 Attach Gateway，所以也沒有真正的使用 Policy 這個 Feature。",[19,3386,3387],{},[32,3388,3389],{},"確認 Runtime 沒有產生額外費用",[19,3391,3392],{},"AgentCore Runtime 是按 CPU 和記憶體的秒級消耗來計費的。我需要確保沒有遺留的 Runtime 在背景持續運作，或者跟 Gateway 掛鉤產生連鎖費用。",[19,3394,3395],{},"檢查結果：沒有任何遺留資源在跑。",[19,3397,3398],{},[32,3399,3400],{},"CloudTrail",[19,3402,3403],{},"我拉出了那段時間的 CloudTrail 紀錄，逐筆檢查跟 AgentCore 相關的 API 呼叫。",[19,3405,3406,3407,3410],{},"最終鎖定是 ",[751,3408,3409],{},"StartPolicyGeneration"," 這個 API 呼叫。從紀錄上看，我確實只有呼叫了3次，請求量完全不合理對應到那個帳單金額。",[19,3412,3413],{},[32,3414,3415],{},"結論：應該不是我的使用量有問題，是計費那邊有問題。",[61,3417,3419],{"id":3418},"step-3跟-support-同步","Step 3：跟 Support 同步",[19,3421,3422],{},"我把 CloudTrail 的排查結果整理好，回覆到 Support Ticket 上。附上了：",[26,3424,3425,3428,3431],{},[29,3426,3427],{},"明確的 API 呼叫時間和次數",[29,3429,3430],{},"計費金額的不合理性說明",[29,3432,3433],{},"我這邊已經確認沒有遺留資源",[61,3435,3437],{"id":3436},"step-4aws-確認是計費-bug","Step 4：AWS 確認是計費 Bug",[19,3439,3440],{},"AWS Support 將 case 轉給了 Bedrock 團隊。Bedrock 團隊調查後確認：",[16,3442,3443],{},[19,3444,3445],{},[32,3446,3447],{},"Cedar Policy Generator 存在計費問題，導致實際計費金額遠超正常使用量應有的費用。",[19,3449,3450,3451,3454],{},"他們修復了這個計費 bug，並且",[32,3452,3453],{},"校正了帳單","。",[19,3456,3457],{},"結案。",[11,3459,3460],{"id":3460},"心理狀態",[19,3462,3463],{},"看到 $14,000 這個數字的時候，腦袋裡跑過各種最壞的劇本——會不會要自己賠？這是我好幾個月的薪水總和，光想就覺得可怕。",[19,3465,3466],{},"即使理性上告訴自己先查原因再說，甚至基本上確定不是我這邊的問題，但焦慮感還是壓不住。",[19,3468,3469],{},"這幾天嚴重睡眠不足，每天躺在床上腦袋還在轉「到底是哪裡出問題」。腸胃也跟著出狀況，一直拉肚子。壓力對身體的影響比我想像中來得直接。",[19,3471,3472],{},"最後當 CloudTrail 的證據越來越明確指向計費問題，Support 也確認 Bedrock 團隊發現問題並正在進行修復，我的心情才開始慢慢平復。",[11,3474,3475],{"id":3475},"事後反思",[19,3477,3478],{},"雖然這次最後證實是 AWS 的計費 bug，但整個事件讓我學到了很多。",[61,3480,3482],{"id":3481},"_1-工作紀錄真的很重要","1. 工作紀錄真的很重要",[19,3484,3485],{},"當下會感到慌張的原因，很大一部分來自 Context 不足，一來我不確定 Agentcore Policy 是如何計費，為何可以用到那麼貴？二來我不知道我5天前具體做了什麼操作。",[19,3487,3488],{},"如果我當初 survey 的時候沒有留下操作紀錄，排查的時候會更加困難。CloudTrail 能幫你查到 API 呼叫，但你自己當時在做什麼、為什麼做，這些 context 只有你自己知道。",[19,3490,3491,3494],{},[32,3492,3493],{},"養成習慣：每次操作不熟的雲服務時，簡單記錄一下你做了什麼。"," 不需要多詳細，一個簡單的筆記或是 Slack 訊息就夠了。關鍵時刻這些紀錄可以救你一命。",[61,3496,3498],{"id":3497},"_2-使用前搞懂計費方式","2. 使用前搞懂計費方式",[19,3500,3501],{},"這聽起來像廢話，但真的很多人（包括我）在 survey 新服務的時候會直接跳進去玩，不會先仔細看定價頁面。",[26,3503,3504,3507,3510],{},[29,3505,3506],{},"開始 survey 前，先看過定價頁面",[29,3508,3509],{},"特別注意按量計費的服務，搞清楚「量」是怎麼定義的",[29,3511,3512],{},"開發帳號最好設定 Budget Alert，超過閾值自動通知",[61,3514,3516],{"id":3515},"_3-先了解公司的處理流程","3. 先了解公司的處理流程",[19,3518,3519],{},"事發的時候，我其實不太確定公司對這種事情的態度和處理方式。後來跟主管報告時，主管第一句話就是：",[16,3521,3522],{},[19,3523,3524],{},[32,3525,3526],{},"「不可能叫你賠的，先搞清楚狀況就好。」",[19,3528,3529],{},"這句話讓我放下了很大的心理負擔。每間公司的文化不同，但我想大部分公司都不會因為合理操作導致的意外費用而讓員工賠償。",[11,3531,3532],{"id":3532},"結語",[19,3534,3535],{},"回頭看這件事，蠻慶幸最後不是我的問題，也慶幸公司的主管很 Nice",[19,3537,3538],{},"這次經歷讓我建立起了面對雲端成本異常的 SOP。以前覺得帳單管理是 FinOps 團隊的事，現在覺得每個會碰到雲服務的工程師都應該有基本的成本意識。",[19,3540,3541],{},"題外話，這讓我想到我大學時期第一次買股票的時候，我買了3股台積電花了大概 2000塊吧，當時每天看著損益正負三四百塊就能很影響我的心情，影響我做事與學習的效率，直到今天可能每天的損益就是一個月的薪水，我還是照常做著自己的事情。我想有了這次經驗，肯定能讓我在未來遇到類似的事情的時候心態更穩健吧。",{"title":402,"searchDepth":403,"depth":403,"links":3543},[3544,3545,3546,3547,3553,3554,3559],{"id":3250,"depth":403,"text":3251},{"id":3261,"depth":403,"text":3261},{"id":3314,"depth":403,"text":3314},{"id":3333,"depth":403,"text":3333,"children":3548},[3549,3550,3551,3552],{"id":3336,"depth":409,"text":3337},{"id":3343,"depth":409,"text":3344},{"id":3418,"depth":409,"text":3419},{"id":3436,"depth":409,"text":3437},{"id":3460,"depth":403,"text":3460},{"id":3475,"depth":403,"text":3475,"children":3555},[3556,3557,3558],{"id":3481,"depth":409,"text":3482},{"id":3497,"depth":409,"text":3498},{"id":3515,"depth":409,"text":3516},{"id":3532,"depth":403,"text":3532},"2026-03-18","Survey AWS AgentCore Policy完，過了幾天以後才發現帳單噴了14000...","/images/blog/20260304-troublemaker/banner.png",{},"/blog/20260304-troublemaker",{"title":3235,"description":3561},"blog/20260304-troublemaker",[3568,3569,3570,3571,3572,3573,3574],"AWS","雲端","成本控管","經驗分享","踩雷","DevOps","雲服務","6QyxVCpq8RjfovhyvoS0butlFVU7bQKJ1pfTGyL4M1Q",1774237783325]