教你如何用VScode写出规范的Python代码

借助于VScode对flake8和yapf的支持,我们将用这两款工具把我们的代码规范化。

首先介绍一下,flake8是python静态代码检查工具,而yapf(python代码格式化工具)的设置

在命令行下安装好flake8和yapf,也就是VScode当中的终端或者自己的命令行也可以,注意,是要在vscode运行的环境当中安装。

(base) user@desktop:~/$ pip install flake8
Collecting flake8
  Downloading https://files.pythonhosted.org/packages/f8/1f/7ea40d1e4146ea55dbab41cda1376db092a75794914169aabd7e8d7a7def/flake8-3.7.9-py2.py3-none-any.whl (69kB)
     |████████████████████████████████| 71kB 42kB/s 
Requirement already satisfied: pycodestyle<2.6.0,>=2.5.0 in /home/yao_lu/anaconda3/lib/python3.7/site-packages (from flake8) (2.5.0)
Requirement already satisfied: entrypoints<0.4.0,>=0.3.0 in /home/yao_lu/anaconda3/lib/python3.7/site-packages (from flake8) (0.3)
Requirement already satisfied: pyflakes<2.2.0,>=2.1.0 in /home/yao_lu/anaconda3/lib/python3.7/site-packages (from flake8) (2.1.1)
Requirement already satisfied: mccabe<0.7.0,>=0.6.0 in /home/yao_lu/anaconda3/lib/python3.7/site-packages (from flake8) (0.6.1)
Installing collected packages: flake8
Successfully installed flake8-3.7.9
(base) user@desktop:~/$ pip install yapf
Collecting yapf
  Downloading https://files.pythonhosted.org/packages/7c/21/534d143afd3df9cae9b21674fcc32207cb80cfb3de56b89ef7a37c746cca/yapf-0.29.0-py2.py3-none-any.whl (185kB)
     |████████████████████████████████| 194kB 190kB/s 
Installing collected packages: yapf
Successfully installed yapf-0.29.0

然后在vscode中的用户设置(settings.json)中添加以下两行即可,现在的vscode应该是可以进行选择,搜索关键词flake8和formatting就能找到。

"python.linting.flake8Enabled": true,
"on.formatting.provider": "yapf",


这样在你保存代码当中,如果不满足flake8规范的地方都会给标记出来,然后按照他的标记修改就好了。对于快速格式化代码就可以直接在代码界面右键选择格式化即可。

如果想要稍微违背一下flake8的规范使得每行的代码超过79个字符呢,可以在python.linting.flake8Args修改--max-line-length=256。这样就能扩大字符限制。


教你如何用VScode写出规范的Python代码_第1张图片

恭喜你,代码又规范了。

你可能感兴趣的:(教你如何用VScode写出规范的Python代码)