当前位置: 首页 > 工具软件 > YAPF > 使用案例 >

在vscode中使用yapf,并手动修改yapf的配置

吴单鹗
2023-12-01

下面的方法同时适用于Linux和Windows平台

参考:GitHub - google/yapf: A formatter for Python files

安装yapf

pip install yapf

手动导出yapf的配置文件,命令行中运行

yapf --style-help > yapf_style.cfg

手动修改yapf的配置,修改自己想修改的配置项

vim yapf_style.cfg

将yapf_style.cfg放在工程目录下,或者与要格式化的文件在同一目录

如果想一劳永逸的话,可以将yapf_style.cfg改名为style,直接放入$HOME/.config/yapf/下,其中HOME目录在windows上需要自己设置添加进PATH,Linux和Mac os就是~,这时vscode配置里yapfArgs可以不写入。


YAPF Github上的说明:

YAPF will search for the formatting style in the following manner:

  1. Specified on the command line
  2. In the [style] section of a .style.yapf file in either the current directory or one of its parent directories.
  3. In the [yapf] section of a setup.cfg file in either the current directory or one of its parent directories.
  4. In the ~/.config/yapf/style file in your home directory.

If none of those files are found, the default style is used (PEP8).

详细可以参考YAPF的Github主页


在vscode中使用yapf,并加载自己修改后的配置文件yapf_style.cfg

    "python.formatting.provider": "yapf",
    "python.formatting.yapfArgs": [
        "--sytle={based_on_style: yapf, indent_width: 4, column_limit: 120}"
    ],

另外给出autopep8的一些配置:

    "python.formatting.autopep8Args": [
        "--max-line-length=120",
    ],

flake8的配置

    "python.linting.flake8Enabled": true,
    "python.linting.lintOnSave": true,
    "python.linting.flake8Args": [
        "--max-line-length=120",
        "--ignore=E501, E262",
    ],

black的配置

    "python.linting.blackArgs": [
        "--line-length", "120",
        "--skip-string-normalization",
    ],

参考:【解决vscode中yapf无法格式化python代码的问题】

 类似资料: