我有一些Python代码具有不一致的缩进.有很多标签和空格的混合使事情变得更糟,甚至空间压痕也不会被保留.
代码按预期工作,但很难维护.
如何在不破坏代码的情况下修复缩进(如HTML Tidy,但对于Python)?
Ale*_*lli 275
使用reindent.py您在Tools/scripts/Python安装目录中找到的脚本:
更改Python(.py)文件以使用4空格缩进而不使用硬标签字符.还可以从行的末尾修剪多余的空格和制表符,并删除文件末尾的空行.还要确保最后一行以换行符结尾.
有关详细的使用说明,请查看该脚本.
eph*_*ent 55
*: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.
例如,如果您只是输入
:ret
所有标签都会扩展为空格.
你可能想要
:se et " shorthand for :set expandtab
确保任何新行都不会使用文字标签.
如果你不使用Vim,
perl -i.bak -pe "s/\t/' 'x(8-pos()%8)/eg" file.py
将替换制表符与空格,假设制表符每8个字符停止file.py(原始的file.py.bak,以防万一).如果您的制表符每4个空格,则将4s替换为4s.
And*_*den 48
我会达到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
Run Code Online (Sandbox Code Playgroud)
注意:E101和E121是pep8缩进(我认为你可以简单地通过--select=E1修复所有与缩进相关的问题 - 从E1开始).
您可以使用递归标志将其应用于整个项目:
$ autopep8 package_dir --recursive --select=E101,E121 --in-place
Run Code Online (Sandbox Code Playgroud)
Ped*_*ito 35
使用autopep8
autopep8 -i script.py 自动格式化Python代码以符合autopep8
PEP 8指南.它使用pep8实用程序来确定
nullstyle需要格式化的部分.nullcode能够解决大部分autopep8可以报告的
问题nullformatting.
pip install autopep8
autopep8 script.py # print only
autopep8 -i script.py # write file
Run Code Online (Sandbox Code Playgroud)
Ben*_*hes 11
使用Vim,它不应该比打击更多Esc,然后键入...
:%s/\t/ /g
Run Code Online (Sandbox Code Playgroud)
...在您要更改的文件上.这会将所有标签转换为四个空格.如果你的间距也不一致,那就更难了.
由于缺少一些模块,重新缩进脚本对我不起作用。无论如何,我发现这个sed命令非常适合我:
sed -r 's/^([ ]*)([^ ])/\1\1\2/' file.py
Run Code Online (Sandbox Code Playgroud)
在大多数类似UNIX的系统上,您还可以运行:
expand -t4 oldfilename.py > newfilename.py
Run Code Online (Sandbox Code Playgroud)
在命令行中,如果要用多个空格(而不是4)替换制表符,请更改数字。您可以轻松编写一个Shell脚本来一次处理一堆文件,并保留原始文件名。
| 归档时间: |
|
| 查看次数: |
237978 次 |
| 最近记录: |