Autopep8簡介
官方解釋:autopep8 automatically formats Python code to conform to the PEP 8 style guide. It uses the pycodestyle 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 pycodestyle.
官網地址:https://pypi.org/project/autopep8/#installation
Python語言的編碼遵從PEP8規范,Autopep8工具能夠依據PEP8規范,快速對代碼文件進行規范檢查並自動排版。對於變量名,類名,函數名等,會給出提示信息,需要工程師手動修改。
Autopep8的安裝。有了pip工具,可以用命令輕松安裝:
$ pip install autopep8
Autopep8的命令行格式運行:
$ autopep8 --in-place --aggressive --aggressive <filename>
在Pycharm中集成Autopep8:
Step1:
File -> Settings… ->Tools -> External Tools -> 點擊“+”號添加
Step2:
在添加界面,有5處需要添加
Name:autopep8
Program:C:\Python27\Scripts\autopep8.exe(在python的Scripts目錄下)
Arguments:--in-place --aggressive --aggressive $FilePath$
Working directory:$ProjectFileDir$
Output filters:$FILE_PATH$\:$LINE$\:$COLUMN$\:.*
配置完成后,點擊OK結束。
Step3:
右鍵點擊需要規范的文件,在菜單中找到External Tools -> autopep8。完成!
規范完了之后,文件中存在一些波浪線的代碼,就是需要手動修改的地方。
上面是完全按照標准的PEP8規范進行代碼格式化的。但是有一些規范,可以忽略,此時可以在Parameters中加入—ignore參數。如:
Parameters:--in-place --aggressive --ignore=E123,E133,E50 $FilePath$
--ignore后面的E123等就是PEP8的規范代號,具體所指的規則,可以在這里查看到:
https://pep8.readthedocs.io/en/latest/intro.html#configuration
用戶可以根據需要,添加需要忽略的規則。