简体   繁体   English

如何修复 Python 缩进

[英]How to fix Python indentation

I have some Python code that have inconsistent indentation.我有一些具有不一致缩进的 Python 代码。 There is a lot of mixture of tabs and spaces to make the matter even worse, and even space indentation is not preserved.有很多制表符和空格的混合使事情变得更糟,甚至空格缩进也没有保留。

The code works as expected, but it's difficult to maintain.代码按预期工作,但很难维护。

How can I fix the indentation (like HTML Tidy , but for Python) without breaking the code?如何在不破坏代码的情况下修复缩进(如HTML Tidy ,但适用于 Python)?

Use the reindent.py script that you find in the Tools/scripts/ directory of your Python installation:使用在 Python 安装的Tools/scripts/目录中找到的reindent.py脚本:

Change Python (.py) files to use 4-space indents and no hard tab characters.更改 Python (.py) 文件以使用 4 个空格缩进并且没有硬制表符。 Also trim excess spaces and tabs from ends of lines, and remove empty lines at the end of files.还要修剪行尾多余的空格和制表符,并删除文件末尾的空行。 Also ensure the last line ends with a newline.还要确保最后一行以换行符结尾。

Have a look at that script for detailed usage instructions.查看该脚本以获取详细的使用说明。


NOTE: If your linux distro does not have reindent installed by default with Python:注意:如果你的 Linux 发行版没有默认安装 Python 的 reindent:

Many linux distros do not have reindent installed by default with python --> one easy way to get reindent is to do pip install reindent .许多 linux 发行版默认没有使用python安装reindent --> 获得reindent一种简单方法是执行pip install reindent

ps An alternative to pip is to use your distros package manager (ie apt-get , yum , dnf ) but then you need to figure out what package has the command line tool because each distro has the tool in a different package. ps pip的替代方法是使用您的发行版包管理器(即apt-getyumdnf ),但是您需要弄清楚哪个包具有命令行工具,因为每个发行版在不同的包中都有该工具。

I would reach for autopep8 to do this:我会使用autopep8来做到这一点:

$ # see what changes it would make
$ autopep8 path/to/file.py --select=E101,E121 --diff

$ # make these changes
$ autopep8 path/to/file.py --select=E101,E121 --in-place

Note: E101 and E121 are pep8 indentation (I think you can simply pass --select=E1 to fix all indentation related issues - those starting with E1).注意: E101 和 E121是 pep8 缩进(我认为您可以简单地传递--select=E1来修复所有与缩进相关的问题 - 那些以 E1 开头的问题)。

You can apply this to your entire project using recursive flag:您可以使用递归标志将其应用于整个项目:

$ autopep8 package_dir --recursive --select=E101,E121 --in-place

See also Tool to convert Python code to be PEP8 compliant .另请参阅将 Python 代码转换为符合 PEP8 的工具

If you're using Vim , see :h retab .如果您使用Vim ,请参阅:h retab

*:ret* *:retab*
:[range]ret[ab][!] [new_tabstop]
                        Replace all sequences of white-space containing a
                        <Tab> with new strings of white-space using the new
                        tabstop value given.  If you do not specify a new
                        tabstop size or it is zero, Vim uses the current value
                        of 'tabstop'.
                        The current value of 'tabstop' is always used to
                        compute the width of existing tabs.
                        With !, Vim also replaces strings of only normal
                        spaces with tabs where appropriate.
                        With 'expandtab' on, Vim replaces all tabs with the
                        appropriate number of spaces.
                        This command sets 'tabstop' to the new value given,
                        and if performed on the whole file, which is default,
                        should not make any visible change.
                        Careful: This command modifies any <Tab> characters
                        inside of strings in a C program.  Use "\t" to avoid
                        this (that's a good habit anyway).
                        ":retab!" may also change a sequence of spaces by
                        <Tab> characters, which can mess up a printf().
                        {not in Vi}
                        Not available when |+ex_extra| feature was disabled at
                        compile time.

For example, if you simply type例如,如果您只需键入

:ret

all your tabs will be expanded into spaces.您的所有选项卡都将扩展为空格。

You may want to你可能想要

:se et  " shorthand for :set expandtab

to make sure that any new lines will not use literal tabs.确保任何新行都不会使用文字制表符。


If you're not using Vim,如果你不使用 Vim,

perl -i.bak -pe "s/\t/' 'x(8-pos()%8)/eg" file.py

will replace tabs with spaces, assuming tab stops every 8 characters, in file.py (with the original going to file.py.bak , just in case).将用空格替换制表符,假设在file.py每 8 个字符停止一个制表file.py (原始文件转到file.py.bak ,以防万一)。 Replace the 8s with 4s if your tab stops are every 4 spaces instead.如果您的制表位是每 4 个空格,则将 8s 替换为 4s。

autopep8 -i script.py

Use autopep8使用autopep8

autopep8 automagically formats Python code to conform to the PEP 8 nullstyle guide. autopep8自动格式化 Python 代码以符合PEP 8 nullstyle指南。 It uses the pep8 utility to determine what parts of the nullcode needs to be formatted.它使用pep8实用程序来确定需要格式化nullcode哪些部分。 autopep8 is capable of fixing most of the nullformatting issues that can be reported by pep8 . autopep8能够修复大多数可由pep8报告的pep8 nullformatting问题。

pip install autopep8
autopep8 script.py    # print only
autopep8 -i script.py # write file

Using Vim, it shouldn't be more involved than hitting Esc , and then typing...使用 Vim,它不应该比点击Esc更复杂,然后输入...

:%s/\t/    /g

...on the file you want to change. ...在您要更改的文件上。 That will convert all tabs to four spaces.这会将所有制表符转换为四个空格。 If you have inconsistent spacing as well, then that will be more difficult.如果您的间距也不一致,那将更加困难。

There is also PythonTidy (since you said you like HTML Tidy).还有PythonTidy (因为你说你喜欢 HTML Tidy)。

It can do a lot more than just clean up tabs though.不过,它可以做的不仅仅是清理标签。 If you like that type of thing, it's worth a look.如果你喜欢这种类型的东西,那么值得一看。

On most UNIX-like systems, you can also run:在大多数类 UNIX 系统上,您还可以运行:

expand -t4 oldfilename.py > newfilename.py

from the command line, changing the number if you want to replace tabs with a number of spaces other than 4. You can easily write a shell script to do this with a bunch of files at once, retaining the original file names.从命令行,如果您想用 4 以外的多个空格替换制表符,请更改数字。您可以轻松编写一个 shell 脚本来同时处理一堆文件,同时保留原始文件名。

The reindent script did not work for me, due to some missing module.由于缺少一些模块,reindent 脚本对我不起作用。 Anyway, I found this sed command which does the job perfect for me:无论如何,我发现这个sed命令非常适合我:

sed -r 's/^([  ]*)([^ ])/\1\1\2/' file.py

If you're lazy (like me), you can also download a trial version of Wingware Python IDE, which has an auto-fix tool for messed up indentation.如果你很懒(像我一样),你也可以下载 Wingware Python IDE 的试用版,它有一个自动修复工具来处理混乱的缩进。 It works pretty well.它工作得很好。 http://www.wingware.com/ http://www.wingware.com/

Try Emacs.试试 Emacs。 It has good support for indentation needed in Python.它对 Python 中所需的缩进有很好的支持。 Please check this link http://python.about.com/b/2007/09/24/emacs-tips-for-python-programmers.htm请检查此链接http://python.about.com/b/2007/09/24/emacs-tips-for-python-programmers.htm

尝试IDLE ,并使用Alt + X查找缩进。

I have a simple solution for this problem.对于这个问题,我有一个简单的解决方案。 You can first type ":retab" and then ":retab!", then everything would be fine你可以先输入":retab"然后输入":retab!",然后一切都会好的

In case of trying to find tool to make your 2-space indented python script to a tab indented version, just use this online tool:如果试图找到将2-space indented Python 脚本制作为tab indented版本的工具,只需使用此在线工具:

https://www.tutorialspoint.com/online_python_formatter.htm https://www.tutorialspoint.com/online_python_formatter.htm

There is also a Google awesome project called YAPF还有一个叫YAPF的 Google 很棒的项目

It can automatically reformat the whole project or check if the project has correct indentation/format.它可以自动重新格式化整个项目或检查项目是否有正确的缩进/格式。 I used that in a commercial project and I recommend that.我在一个商业项目中使用了它,我推荐它。

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

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