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

我有一些现有的代码,它们的格式不一致——有时候两个空格用于缩进,有时候四个,等等。代码本身是正确的,经过了良好的测试,但是格式很糟糕。

有没有一个网上的地方,我可以简单地粘贴 Python 代码片段,并让它自动缩进/格式化为我?或者,是否有一个 X,这样我就可以做类似于 X --input=*.py的东西,让它覆盖每个文件与格式化版本?

129629 次浏览

Edit: 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.


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.

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

Some editors have an auto-format feature that does this for you. Eclipse is one example (though you would probably have to install a python plug-in).

Have you checked whichever editor you use for such a feature?

autopep8

autopep8 would auto-format your python script. not only the code indentation, but also other coding spacing styles. It makes your python script to conform PEP8 Style Guide.

pip install autopep8
autopep8 your_script.py    # dry-run, only print
autopep8 -i your_script.py # replace content

Update:

Many editors have pep8 plugins that automatically reformat your code right after you save the file. py-autopep8 in emacs

yapf

yapf is a new and better python code formatter. which tries to get the best formatting, not just to conform the guidelines. The usage is quite the same as autopep8.

pip install yapf
yapf your_script.py    # dry-run, only print
yapf -i your_script.py # replace content

For more information, like formatting configurations, please read the README.rst on yapf github


Update 2:

Black

Black is much better than yapf. It's smarter and fits most complex formatting cases.

Found an offline solution with PyCharm

In PyCharm do:

1. Select all the Code:

[ctrl]+[A]

2. Format all the Code

[ctrl]+[alt]+[L]

Use black. It has deliberately only one option (line length) to ensure consistency across many projects. It enforces PEP8.

Well you can simply use code editors/ interpreters like:-

  1. Visual Studio Code
  2. Sublime Text
  3. Pycharm(IDE)
  4. Spyder(IDE)

As per my experience Visual studio code has a great feature of auto formatting the code after you save it.

I am currently utilizing Ubuntu 18.04 LTS and VSC as a python IDE. My version of python is 3.10.5. I have noticed a difficulty in utilizing the python interpreter on my computer with the one used on bash. Reformatting has been one of those difficulties, although VSC does allow auto formatting it doesn't seem to work on my system. One workaround, using pip as a way to install separate python related libraries, is to install black using pip:

$ pip install black

after installing, simply utilize the command:

$ black <name of your python file.py>

This will directly alter and reformat the .py file and properly reformat your code.