简体   繁体   English

如何在 PyCharm 中为 flake8 启用自动代码格式化

[英]How do I enable auto code formatting for flake8 in PyCharm

I use Tox to run unit tests, with a flake8 command that checks for code formatting errors.我使用 Tox 运行单元测试,使用 flake8 命令检查代码格式错误。 Each time I code in PyCharm, I run tox then realise I have a bunch of annoying formatting errors I have to back and manually fix.每次我在 PyCharm 中编码时,我都会运行 tox 然后意识到我有一堆烦人的格式错误,我必须返回并手动修复。 I would like PyCharm to automatically format the code (according to flake8 google for me each time it auto-saves after I stop typing.我希望 PyCharm 自动格式化代码(根据 flake8 google 在我停止打字后每次自动保存时为我提供的信息。

my tox testenv looks like this:我的 tox testenv 看起来像这样:

[testenv:flake8]
commands=flake8 <my_code_directory>
deps =     
  flake8==2.4.1    
  flake8-import-order==0.11    
  pep8-naming==0.4.1 

[flake8] 
max-line-length = 120 
import-order-style = google

Is this possible?这可能吗? Do I have to download a specific plugin somewhere?我必须在某处下载特定的插件吗? If not with flake8, what about just PEP-8?如果没有 flake8,那么只有 PEP-8 怎么样?

Flake8 and import ordering are not auto-fixable in a way that complies with what you're seeing. Flake8 和导入排序不能以符合您所看到的方式自动修复。 You can auto-fix pep8 with autopep8.您可以使用 autopep8 自动修复 pep8。

There are discussions here about implementing this for Flake8 though.有讨论,这里大约尽管实现这个为Flake8。

For automatically sorting import statements use isort .对于自动排序导入语句,请使用isort Consider using black to auto-format your Python code.考虑使用黑色来自动格式化你的 Python 代码。

The tool you want is probably autopep8 .您想要的工具可能是autopep8 This is especially because the warning codes it uses correspond to the flake8 ones.这尤其是因为它使用的警告代码对应于 flake8 的警告代码。

For example, if you want to autofix all instances of E701 multiple statements on a single line warning, run the following例如,如果要在单行警告上自动修复 E701 多个语句的所有实例,请运行以下命令

for f in `find -name "*.py"`; do autopep8 --in-place --select=E701 $f; done

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM