将Python代码转换为符合PEP8的工具 [英] Tool to convert Python code to be PEP8 compliant
问题描述
我知道有一些工具可以验证您的Python代码是否符合PEP8,例如,在线服务< a>和 python模块。
但是,我找不到可以将我的Python文件转换为自包含的PEP8有效Python文件的服务或模块。有没有人知道是否有什么?
我认为这是可行的,因为PEP8是关于代码的外观,对吗?
您可以使用 autopep8 !虽然你让自己一杯咖啡,这个工具很高兴地删除所有那些讨厌的PEP8违反,不会改变代码的含义。
通过pip安装:
pip install autopep8
将此应用于特定文件:
autopep8 py_file --in-place
或递归到您的项目, verbose选项会给您一些反馈:
autopep8 project_dir --recursive --in-place --pep8-passes 2000 --verbose
注意:有时默认的100遍不够,我把它设置为2000合理地高,并且将捕获除了最麻烦的文件之外的所有文件(它一旦发现没有可解决的pep8违规就停止传递)...
> 如果您要满足PEP8合规性:我使用的一个策略是运行上面的autopep8,然后运行PEP8,打印剩余的违规(文件,行号和什么): pep8 project_dir --ignore = E501
pep8 project_dir --ignore = E501
并手动单独更改注意:autopep8提供了一个 - aggressive
参数(无情的) 修复这些意义改变的违规),但要小心如果你使用侵略性你可能必须调试...(例如在numpy / pandas True == np.bool_(True)
但不是 True is np.bool_(True)
!)
每种类型(前后)有多少违规:
pep8 --quiet --statistics。
注意:我认为E501s(行太长)是一种特殊情况,因为可能会有很多
I know there are tools which validate whether your Python code is compliant with PEP8, for example there is both an online service and a python module.
However, I cannot find a service or module which can convert my Python file to a self-contained, PEP8 valid Python file. Does anyone know if there are any?
I assume it's feasible since PEP8 is all about the appearance of the code, right?
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.
Install it via pip:
pip install autopep8
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!
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.
这篇关于将Python代码转换为符合PEP8的工具的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!