如何自动格式化一些 Python 代码以正确格式化?

2022-01-12 00:00:00 python formatting

问题描述

我有一些现有的代码格式不一致——有时两个空格用于缩进,有时四个空格等等.代码本身是正确且经过充分测试的,但格式很糟糕.

I have some existing code which isn't formatted consistently -- sometimes two spaces are used for indent, sometimes four, and so on. The code itself is correct and well-tested, but the formatting is awful.

网上有没有一个地方可以让我简单地粘贴一段 Python 代码并自动为我缩进/格式化?或者,是否有一个 X 以便我可以执行类似 X --input=*.py 之类的操作并让它用格式化版本覆盖每个文件?

Is there a place online where I can simply paste a snippet of Python code and have it be indented/formatted automatically for me? Alternatively, is there an X such that I can do something like X --input=*.py and have it overwrite each file with a formatted version?


解决方案

现在,我会推荐 autopep8,因为它不仅可以纠正缩进问题,而且(由您自行决定)使代码符合许多其他 PEP8 准则.

Nowadays, I would recommend autopep8, since it not only corrects indentation problems but also (at your discretion) makes code conform to many other PEP8 guidelines.

使用 reindent.py.它应该与 Python 的标准发行版一起提供,但在 Ubuntu 上您需要安装 python2.6-examples 包.

Use reindent.py. It should come with the standard distribution of Python, though on Ubuntu you need to install the python2.6-examples package.

您也可以在 网络上找到它.

You can also find it on the web.

此脚本尝试将任何 python 脚本转换为符合 4-space 标准.

This script attempts to convert any python script to conform with the 4-space standard.

相关文章