在 VSCode 中使用 Black 格式化 Python 时出现配置错误

问题描述 投票:0回答:1

在 VSCode 中保存时无法设置黑色格式。

  • 我完成了黑色的步骤docs
  • 安装了 VSCode 插件:black formatterpython
  • 设置个人配置(我也在项目范围内尝试了相同的配置
    .vscode/settings.json
    ):
  "[python]": {
    "editor.defaultFormatter": "ms-python.black-formatter",
    "editor.formatOnSave": true,
    "editor.formatOnSaveMode": "file",
    "editor.tabSize": 4,
    "editor.codeActionsOnSave": {
      "source.organizeImports": "explicit"
    }
  },

我正在使用 pipenv 设置我的环境

pipenv shell
pipenv install --dev black
。 我还设置了我的
Python: Select Interpreter
并指出了我的环境。

这是我的 Pipfile:

[dev-packages]
black = ">=24.2.0"
faker = ">=23.0.0"
pylint = "*"

[requires]
python_version = "3.11"

这是我的

pyproject.toml
:

[tool.black]
color = true
diff = true
verbose = true
line-length = 88
target-version = ['py311']
include = '.lib/etl/.*/*.py'
required-version = "24.2.0"

我尝试使用环境(Pipenv)

black = ">=24.2.0"
并在我的系统中安装
brew install black-sat/black/black-sat
并获得相同的结果。

版本:

  • VS代码:1.86.2
  • 系统:MacOS Apple M1 Pro
  • 黑色:
    24.2.0

问题

当我选择格式化程序并格式化代码时,我得到以下结果:

之前:

之后:

从 CLI 运行

如果运行

pipenv run black .
,它会正确检测到我的
pyproject.toml
black
args

❯ pipenv run black .                
Identified `/<project-path>/<project>` as project root containing a .git directory.
Using configuration from project root.
color: True
diff: True
verbose: True
line_length: 88
target_version: ['py311']
include: .lib/etl/.*/*.py
required_version: 24.2.0
...
@@ -11,14 +11,7 @@
 
     return add(a, b)
 
 
 def add(a, b):
-
-
-
-
-
-
-    
     """Add two numbers"""
     return a + b
would reformat /<path-to-file>/index.py
python visual-studio-code pipenv python-black
1个回答
0
投票

我已经按照这个操作并成功安装了黑色格式化程序。我不知道这是否对你有帮助,但这就是我所做的。

更改这些 vs-code 首选项(文件>首选项>设置): (如果没有参考则转到步骤4)

"[python]": {
   "editor.defaultFormatter": "ms-python.python",
   "editor.formatOnSave": true,
   "editor.formatOnPaste": true,
   "editor.formatOnType": true,
   "python.formatting.provider": "black",
   "python.formatting.blackPath": "black"
  }
  1. 转到随机项目 python 文件并保存 3 如果弹出“未安装Formatter black”的消息。单击“是”并安装在项目的环境中。
  2. 如果您来自第 1 步,请执行 pip install black 并从头开始
  3. 你可以走了。
© www.soinside.com 2019 - 2024. All rights reserved.