VsCode 中用 flake8 和 black 来检测和格式化 Python

安装

全局安装 flake8

1
/usr/local/bin/python3 -m pip install -U flake8

全局安装 black

1
/usr/local/bin/python3 -m pip install -U black

配置

1
2
3
4
5
6
"python.languageServer": "Pylance",
"python.linting.flake8Enabled": true,
"python.formatting.provider": "black",
"python.linting.pylintEnabled": false, // 关闭pylint工具
"python.formatting.blackPath": "/usr/local/bin/black",
"python.linting.flake8Path": "/usr/local/bin/flake8",

flake8black 可选参数:

1
2
3
4
5
6
7
"python.linting.flake8Args": [
"--max-line-length=248", // 设置单行最长字符限制
"--ignore=W191, E266, W504"
],
"python.formatting.blackArgs": [
"--line-length=128" // 格式化时单行最长长度
],

排序 import 语句

1
/usr/local/bin/python3 -m pip install -U isort

配置

1
2
3
4
5
"[python]": {
"editor.codeActionsOnSave": {
"source.organizeImports": true
}
},

也可以配置用于全局

1
2
3
"editor.codeActionsOnSave": {
"source.organizeImports": true
},