格式化python代码

  遵循相同的代码风格非常重要,特别是需要和其他开发者一起维护同一个项目。为了帮助大家形成统一的代码风格,Python官方提供了一个基于PEP8的命令行工具:pycodestyle。该工具能够检查Python代码是否符合PEP8规范,并给出提示信息。

1 #安装 pycodestyle
2 ]# pip install pycodestyle

  对于一个或多个文件进行检查,打印检查报告:

  例:

 1 ]# pycodestyle --first dytt2018-001.py
 2 dytt2018-001.py:7:1: E302 expected 2 blank lines, found 1
 3 dytt2018-001.py:8:12: E225 missing whitespace around operator
 4 dytt2018-001.py:8:26: E231 missing whitespace after ':'
 5 dytt2018-001.py:8:80: E501 line too long (138 > 79 characters)
 6 dytt2018-001.py:9:10: E128 continuation line under-indented for visual indent
 7 dytt2018-001.py:10:5: E265 block comment should start with '# '
 8 dytt2018-001.py:13:163: W605 invalid escape sequence '\s'
 9 dytt2018-001.py:36:1: E305 expected 2 blank lines after class or function definition, found 1
10 dytt2018-001.py:45:30: W292 no newline at end of file

  也可以通过 --show-source 显示不符合规范的源码

  通过pycodestyle检查出代码不符合规范的地方,通过手动去一个个去修改,代码少的时候还凑合,如果代码量大的时候就非常麻烦了。这个时候我们可以通过autopep8工具来实现Python代码的自动格式化。

]# autopep8 --in-place dytt2018-001.py
]# pycodestyle --first dytt2018-001.py

]#

  注:如果不包含--in-place参数,则会将autopep8格式化后的参数直接输出到控制台,而不会保存到源文件中。