在 vscode 中使用 Prettier 时格式化 python 的问题

rou*_*cle 2 python visual-studio-code vscode-settings prettier

在 vscode 中,我想使用 Prettier 作为我的默认格式化程序,但不适用于 Python,我将只使用 autopep8。我现在有以下设置:

{
  "workbench.iconTheme": "vscode-icons",
  "workbench.editorAssociations": [
    {
      "viewType": "jupyter.notebook.ipynb",
      "filenamePattern": "*.ipynb"
    }
  ],
  "git.confirmSync": false,
  "editor.formatOnPaste": true,
  "editor.formatOnSave": true,
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "python.formatting.provider": "autopep8",
  "explorer.confirmDelete": false,
  "python.showStartPage": false,
  "explorer.confirmDragAndDrop": false
}
Run Code Online (Sandbox Code Playgroud)

当我保存一个 python 文件时,它给了我消息:“扩展'Pretier - 代码格式化程序无法格式化等......'。所以,显然它仍然使用错误的 python 文件格式化程序。我该如何更改?!

小智 10

@round_circle的答案中有意义的配置片段:

"[python]": {
    "editor.defaultFormatter": "ms-python.python"
  }
Run Code Online (Sandbox Code Playgroud)

添加后,autopep8 可用于 python 文件。


rou*_*cle 7

如果我禁用 Prettier 作为默认格式化程序,它将不再在保存时格式化,但我的 Python 将在保存时由 autopep8 格式化。考虑到这一点,以下解决方案对我有用,让 Prettier 为其他语言工作,autopep8 为 Python 工作:

{
  "workbench.iconTheme": "vscode-icons",
  "workbench.editorAssociations": [
    {
      "viewType": "jupyter.notebook.ipynb",
      "filenamePattern": "*.ipynb"
    }
  ],
  "git.confirmSync": false,
  "editor.formatOnPaste": true,
  "editor.formatOnSave": true,
  "python.formatting.provider": "autopep8",
  "explorer.confirmDelete": false,
  "python.showStartPage": false,
  "explorer.confirmDragAndDrop": false,
  "python.linting.pylintArgs": ["--load-plugins=pylint_django"],
  "javascript.updateImportsOnFileMove.enabled": "always",
  "editor.defaultFormatter": "esbenp.prettier-vscode",
  "[python]": {
    "editor.defaultFormatter": "ms-python.python"
  }
}
Run Code Online (Sandbox Code Playgroud)

如果有人找到更好的解决方案,请告诉我!


小智 5

你可以做 @round_circle 所做的事情,因为这应该有效。如果您不想设置初始提供程序,例如您可能想使用 Black,您也可以添加到 settings.json 中:

"[python]": {
    "editor.defaultFormatter": null
  },
Run Code Online (Sandbox Code Playgroud)

我碰巧使用的是 Microsoft 的 Python 扩展,默认为 autoPep8,这将提示您设置要使用的格式化程序。添加格式化程序的提示照片然后您可以通过添加以下内容在 settings.json 中添加您的提供程序:

"python.formatting.provider": <your_formatter>
Run Code Online (Sandbox Code Playgroud)

这也可以参考这里:VS Code Formatting