如何修复Python缩进

问题:如何修复Python缩进

我有一些缩进不一致的Python代码。制表符和空格的混合使用使情况变得更糟,甚至不保留空格缩进。

该代码可以按预期工作,但是很难维护。

如何在不破坏代码的情况下修复缩进(如HTML Tidy,但对于Python)?

I have some Python code that have inconsistent indentation. 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?


回答 0

使用在Python安装目录中reindent.py找到的脚本Tools/scripts/

更改Python(.py)文件以使用4个空格的缩进,并且不使用硬制表符。还修剪行尾多余的空格和制表符,并删除文件末尾的空行。还要确保最后一行以换行符结尾。

查看该脚本以获取详细的使用说明。

Use the reindent.py script that you find in the Tools/scripts/ directory of your Python installation:

Change Python (.py) files to use 4-space indents and no hard tab characters. 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.


回答 1

如果您使用的是Vim,请参见:h retab

                                                        *:ret * *:retab *
:[range] ret [ab] [!] [new_tabstop]
                        替换所有包含空格的空白序列
                        <Tab>,使用新的空白字符串
                        给出制表符的值。如果不指定新的
                        制表符大小或为零,Vim使用当前值
                        “ tabstop”。
                        'tabstop'的当前值始终用于
                        计算现有标签的宽度。
                        使用!,Vim还将替换仅普通字符串
                        带有制表符的空格。
                        启用“ expandtab”后,Vim将所有选项卡替换为
                        适当数量的空格。
                        此命令将'tabstop'设置为给定的新值,
                        如果对整个文件执行默认设置,
                        不应进行任何可见的更改。
                        注意:此命令修改任何<Tab>字符
                        在C程序中的字符串中。使用“ \ t”避免
                        这(无论如何都是好习惯)。
                        “:重新标记!” 可能还会更改空格序列
                        <Tab>字符,可能会使printf()混乱。
                        {Vi无此功能}
                        | + ex_extra |时不可用 该功能已于禁用
                        编译时间。

例如,如果您只是键入

:ret

您所有的标签都将扩展为空格。

您可能要

:se等::set expandtab的简写

确保任何新行都不会使用文字标签。


如果您不使用Vim,

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

假设制表符每隔8个字符停止,则将用空格替换制表符file.pyfile.py.bak以防万一)。如果制表符停靠符是每4个空格,则用4s替换8s。

If you’re using Vim, see :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,

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). Replace the 8s with 4s if your tab stops are every 4 spaces instead.


回答 2

我会为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

注意:E101和E121是pep8缩进(我认为您可以简单--select=E1地解决所有与缩进有关的问题-以E1开头的问题)。

您可以使用递归标志将其应用于整个项目:

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

另请参阅将Python代码转换为符合PEP8的工具

I would reach for autopep8 to do this:

$ # 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).

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.


回答 3

autopep8 -i script.py

使用autopep8

autopep8 自动格式化Python代码以符合PEP 8 nullstyle指南。它使用该pep8实用程序来确定nullcode需要格式化的哪些部分 。autopep8能够nullformatting解决可以报告的大多数 问题pep8

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

autopep8 -i script.py

Use autopep8

autopep8 automagically formats Python code to conform to the PEP 8 nullstyle guide. It uses the pep8 utility to determine what parts of the nullcode needs to be formatted. autopep8 is capable of fixing most of the nullformatting issues that can be reported by pep8.

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

回答 4

使用Vim,除了点击Esc,然后输入…外,不应该涉及更多内容。

:%s/\t/    /g

…在您要更改的文件上。这会将所有选项卡转换为四个空格。如果间距也不一致,则将更加困难。

Using Vim, it shouldn’t be more involved than hitting Esc, and then typing…

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


回答 5

还有PythonTidy(因为您说过喜欢HTML Tidy)。

它不仅可以清理标签,还可以做更多的事情。如果您喜欢这种类型的东西,那就值得一看。

There is also PythonTidy (since you said you like 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.


回答 6

在大多数类似UNIX的系统上,您还可以运行:

expand -t4 oldfilename.py > newfilename.py

在命令行中,如果要用多个空格(而不是4)替换制表符,请更改数字。您可以轻松编写一个Shell脚本来同时处理一堆文件,并保留原始文件名。

On most UNIX-like systems, you can also run:

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.


回答 7

如果您像我一样懒惰,也可以下载Wingware Python IDE的试用版,该软件具有用于弄乱缩进的自动修复工具。效果很好。 http://www.wingware.com/

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. It works pretty well. http://www.wingware.com/


回答 8

由于缺少某些模块,reindent脚本对我不起作用。无论如何,我发现此sed命令对我来说很完美:

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

The reindent script did not work for me, due to some missing module. Anyway, I found this sed command which does the job perfect for me:

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

回答 9

试试Emacs。它对Python所需的缩进有很好的支持。请检查此链接http://python.about.com/b/2007/09/24/emacs-tips-for-python-programmers.htm

Try Emacs. It has good support for indentation needed in Python. Please check this link http://python.about.com/b/2007/09/24/emacs-tips-for-python-programmers.htm


回答 10

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

Try IDLE, and use Alt + X to find indentation.


回答 11

对于这个问题,我有一个简单的解决方案。您可以先输入“:retab”,然后输入“:retab!”,然后一切都会好起来的

I have a simple solution for this problem. You can first type “:retab” and then “:retab!”, then everything would be fine


回答 12

如果尝试查找将2-space indentedpython脚本转换为tab indented版本的工具,请使用以下在线工具:

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

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:

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