Python 格式化工具選擇與 Black 指令教學

4 分鐘閱讀

琳 avatar

what is the default or 推薦的 python formatter in VSCode?

Felo Search avatar
Felo Search

當您在 VS Code 中編輯 Python 檔案時,格式化工具(Formatter)並不再內建於 Python Extension,而是透過外部擴充功能提供。以下說明預設與常見推薦的 Formatter,以及如何進行設定。

格式化工具簡介

預設 Formatter

推薦的第三方 Formatter

如何設定預設 Formatter

  1. 開啟任一 .py 檔案。
  2. 於編輯區按右鍵,選擇 Format Document With…
  3. 再選 Configure Default Formatter…
  4. 從清單中挑選您要的格式化擴充,例如 ms-python.black-formatterms-python.autopep83

設定完成後,即可透過快捷鍵(Windows/Linux:Shift+Alt+F;macOS:Option+Shift+F)或儲存檔案時自動格式化(於設定中開啟 editor.formatOnSave)來統一程式碼風格。

我後來在 jim60105/standalone-civitai-shortcut 中 採用 black

琳 avatar

how to run python black formatter in command line for specific folder only?

Felo Search avatar
Felo Search

在命令列針對特定資料夾執行 Black 格式化,只需要在指令後面接上該資料夾的路徑即可。以下示範最常用的做法以及進階參數。

前置作業

針對特定資料夾格式化

常用進階選項

範例

假設專案結構如下:

my_project/
├── src/
│   ├── module1.py
│   └── module2.py
└── tests/
    └── test_module.py

要只格式化 src 資料夾,可執行:

black my_project/src

執行後,Black 會在終端顯示被修改或檢查通過的檔案清單。若要一次格式化整個專案,則改為指定 my_project/ 即可4

  1. How to make code formatting work again for Python (Visual ...

  2. VSCode Python项目使用Ruff格式化代码配置指南_文心快码

  3. Formatting Python in VS Code

  4. Format your Python Code using Black | by Achanandhi M ↩2