为VS Code中的Python编码约定设置pycodestyle


我有点沉迷于在VS Code中使用pycodestyle,所以记下

前提

  • VS Code已安装
  • 内置Python 3.7.3环境

程序

安装pycodestyle和Pep8(Pep8是pycodestyle的旧名称)

1
pip install pycodestyle pep8

使用VS Code打开目标目录,并将以下内容写入.vscode/settings.json配置文件(如果不存在则创建文件)

settings.json

1
2
3
4
5
6
{
    "python.linting.enabled": true,
    "python.linting.pylintEnabled": false,
    "python.linting.pep8Enabled": true,
    "python.linting.lintOnSave": true
}

设置

规则无效等时,请在顶层目录中创建一个setup.cfg文件,并在pycodestylepep8部分中两次描述相同的规则设置(当前VS Code为,它与名称更改不对应)。 Pep8→pycodestyle,并且需要双重说明以使其与命令中的Lint兼容)

下面是忽略每行字符限制(少于80个字符)时的配置文件示例。

setup.cfg

1
2
3
4
5
[pycodestyle]
ignore = E501

[pep8]
ignore = E501

使用上述设置,VS Code将自动执行Lint
VSCodeでのLint表示.png

要使用

命令执行Lint,请在顶层目录

中执行以下命令

1
2
$ pycodestyle .
./db_operation.py:127:31: E711 comparison to None should be 'if cond is not None:'