簡體   English   中英

帶有黑色的Python VSCode formatOnSave在WSL中不起作用

[英]Python VSCode formatOnSave with black not working in WSL

我正在使用 WSL2 處理一些 Python 項目,但黑色在 VSCode(遠程 - WSL)中不會自動格式化。

系統信息:

  • 基礎系統:Windows 11 Pro x64
  • WSL2 系統:Ubuntu-22.04-LTS
  • WSL 中的settings.json路徑:/home/<user>/. /home/<user>/.vscode-server/data/Machine/settings.json /data/Machine/settings.json

我的settings.json看起來像:

{
  // Python linting and formatting customizations..
  "python.linting.pylintEnabled": false,
  "python.linting.flake8Enabled": true,
  "python.linting.enabled": true,
  "python.linting.flake8Args": ["--max-line-length=100", "--ignore=E501"],
  "python.formatting.provider": "black",
  "python.formatting.blackArgs": ["--line-length", "100"],
  "[python]": {
    "editor.codeActionsOnSave": {
      "source.organizeImports": true
    },
    "editor.formatOnSave": true
  }
}

同樣的設置適用於我的 Windows 11 系統。 在本地 Windows 中,每當我為 python 項目創建虛擬環境並保存 python 文件時,vscode 會自動要求我在 venv 中安裝flake8black 但在 WSL 中沒有發生任何此類事情。

即使我在 WSL Python venv 中安裝black ,它也不會自動格式化 Python 代碼; 並且在Output > PythonOutput > Log (Main)選項卡中沒有可見的與black相關的日志。

但是在 venv 中安裝black后手動格式化有效:

(venv) asif@MSI:~/vscode/myproject/$ black app_pkg/models.py 
reformatted app_pkg/models.py

All done! ✨ 🍰 ✨
1 file reformatted.

注意:我什至嘗試將"python.formatting.blackPath": "./venv/bin/black"添加到settings.json文件,但沒有成功。

任何幫助將非常感激。 提前致謝!

編輯:正如建議的那樣,我在我的系統中啟用了這兩個設置,普遍應用保存時的格式: 保存設置上的格式 Python 代碼格式化程序設置為black Python 默認格式化程序設置

我仍然無法使 Python formatOnSave在 VSCode-WSL 中工作。

但是在 venv 中安裝 black 后手動格式化有效

可見黑色可以工作。現在我們來為vscode設置自動格式化:

先打開vscode的設置, format on save ,然后勾選。 設置這一步,每次保存文件都會自動排版代碼。

在此處輸入圖像描述

然后搜索Python formatting provider並選擇black

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM