python 格式规范工具 autopep8 Tool to convert Python code to be PEP8 compliant

You can use autopep8

Whilst you make yourself a cup of coffee this tool happily removes all those pesky PEP8 violations which don't change the meaning of the code.

1、Install it via pip:

pip install autopep8

如果pip没有事先安装,其安装方法如下:

apt-get install python-pip

如果安装不成功,采取如下方式:

To install pip, securely download get-pip.py. (下载地址

Then run the following (which may require administrator access):

python get-pip.py

If setuptools is not already installed, get-pip.py will install setuptools for you. [3]

To upgrade an existing setuptools, run pip install -U setuptools.

再次安装,如果提示需要添加参数,采取如下步骤:

提示需要添加--allow-external参数 或者--allow-unverified参数

则在命令行添加: --allow-external  autopep8 或者 --allow-unverified autopep8

2、Apply this to a specific file:

autopep8 py_file --in-place

or to your project (recursively), the verbose option gives you some feedback of how it's going:

autopep8 project_dir --recursive --in-place --pep8-passes 2000 --verbose

Note: Sometimes the default of 100 passes isn't enough, I set it to 2000 as it's reasonably high and will catch all but the most troublesome files (it stops passing once it finds no resolvable pep8 infractions)...

At this point I suggest retesting and doing a commit!

3、If you want "full" PEP8 compliance: one tactic I've used is to run autopep8 as above, then run PEP8, which prints the remaining violations (file, line number, and what):

pep8 project_dir --ignore=E501

and manually change these individually (e.g. E712s - comparison with boolean).

Note: autopep8 offers an --aggressive argument (to ruthlessly "fix" these meaning-changing violations), but beware if you do use aggressive you may have to debug... (e.g. in numpy/pandas True == np.bool_(True) but not True is np.bool_(True)!)

You can check how many violations of each type (before and after):

pep8 --quiet --statistics .

Note: I consider E501s (line too long) are a special case as there will probably be a lot of these in your code and sometimes these are not corrected by autopep8.

As an example, I applied this technique to the pandas code base.

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值