首页 > 解决方案 > 在 vscode 中使用 Prettier 时格式化 python 的问题

问题描述

在 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
}

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

标签: pythonvisual-studio-codevscode-settingsprettier

解决方案


如果我禁用 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"
  }
}

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


推荐阅读