寫Python一段時間了, 但一直有一個壞習慣. 就是沒有很好的去遵守PEP8的rules去寫code. 那平常我又幾乎都用vim來寫python的code. 所以找了相關的套件來幫助我去克服我這個壞習慣.

PEP8

pep8 is a tool to check your Python code against some of the style conventions in PEP 8.

Autopep8

autopep8 automatically formats Python code to conform to the PEP 8 style guide. It uses the pep8 utility to determine what parts of the code needs to be formatted. autopep8 is capable of fixing most of the formatting issues that can be reported by pep8.

根據描述autopep8可以解決大部分pep8語法不對的問題. 但可能有小部分還是要手動處理. 所以才利用這兩個工具結合再一起來解決整個程式符合PEP8 style conventions的問題.

Install

$ pip install pep8
$ pip install autopep8

Usage

> pep8 --first add_ad_cat.py # show first occurrence of each error

add_ad_cat.py:1:1: E265 block comment should start with '# '
add_ad_cat.py:23:1: E402 module level import not at top of file
add_ad_cat.py:26:41: E231 missing whitespace after ','
add_ad_cat.py:28:1: E302 expected 2 blank lines, found 1
add_ad_cat.py:39:12: E221 multiple spaces before operator
add_ad_cat.py:39:31: W291 trailing whitespace
add_ad_cat.py:50:1: W293 blank line contains whitespace
add_ad_cat.py:52:21: E703 statement ends with a semicolon
add_ad_cat.py:54:80: E501 line too long (101 > 79 characters)
add_ad_cat.py:84:7: E111 indentation is not a multiple of four
> pep8 --show-source add_ad_cat.py # show source code for each error
add_ad_cat.py:1:1: E265 block comment should start with '# '
#-*- coding: utf-8 -*-
^
add_ad_cat.py:2:1: E265 block comment should start with '# '
#!/usr/bin/env python3
^
add_ad_cat.py:23:1: E402 module level import not at top of file
from config import settings
^
add_ad_cat.py:24:1: E402 module level import not at top of file
from config import database
^
add_ad_cat.py:26:41: E231 missing whitespace after ','
mc = memcache.Client(['127.0.0.1:11211'],debug=0)
                                        ^
add_ad_cat.py:28:1: E302 expected 2 blank lines, found 1

如上所示 你可以看到哪些地方不符合PEP8, 那如果你想使用autopep8來幫你自動解決上述出現的error化, 你可以使用下面的指令.

> autopep8 --in-place --aggressive add_ad_cat.py
[file:add_ad_cat.py]
--->  Applying global fix for E265
--->  Applying global fix for W602
--->  14 issue(s) to fix {'E221': {39}, 'W291': {39}, 'E703': {52}, 'E402': {24, 23}, 'E231': {26, 84}, 'E265': {1, 2}, 'E501': {59, 75, 54}, 'E302': {28}}
--->  7 issue(s) to fix {'E221': {40}, 'E501': {61}, 'E231': {88}, 'E402': {24, 23}, 'E265': {1, 2}}
--->  5 issue(s) to fix {'E501': {61}, 'E402': {24, 23}, 'E265': {1, 2}}

接著我們在run一次 pep8 --first add_ad_cat.py 看有什麼不一樣

> pep8 --first add_ad_cat.py

add_ad_cat.py:1:1: E265 block comment should start with '# '
add_ad_cat.py:23:1: E402 module level import not at top of file
add_ad_cat.py:60:80: E501 line too long (81 > 79 characters)

你會發現error少了一部分, 但是還是剩一點. 那就表示剩下的部分你要自己手動修啦. 整個修完就大功告成了!

Reference