我有一些缩进不一致的Python代码。制表符和空格的混合使用使情况变得更糟,甚至不保留空格缩进。
该代码按预期工作,但是很难维护。
如何在不破坏代码的情况下修复缩进(如HTML Tidy,但对于Python)?
使用在Python安装目录中reindent.py
找到的脚本Tools/scripts/
:
更改Python(.py)文件以使用4个空格的缩进,并且不使用硬制表符。还修剪行尾多余的空格和制表符,并删除文件末尾的空行。还要确保最后一行以换行符结尾。
查看该脚本以获取详细的使用说明。
*: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.py
(file.py.bak
以防万一)。如果制表符停靠符是每4个空格,则用4s替换8s。
我会为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
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
使用Vim,除了点击Esc,然后输入...外,不应该涉及更多内容。
:%s/\t/ /g
...在您要更改的文件上。这会将所有选项卡转换为四个空格。如果间距也不一致,那将更加困难。
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.
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.
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/
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
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
Try IDLE, and use Alt + X to find indentation.
I have a simple solution for this problem. You can first type ":retab" and then ":retab!", then everything would be fine
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:
文章标签:python
版权声明:本文为原创文章,版权归 admin 所有,欢迎分享本文,转载请保留出处!
评论已关闭!