遵循相同的代碼風格非常重要,特別是需要和其他開發者一起維護同一個項目。為了幫助大家形成統一的代碼風格,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格式化后的參數直接輸出到控制台,而不會保存到源文件中。