python 将python缩进从空格转换为制表符的工具?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/338767/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-03 19:55:30  来源:igfitidea点击:

Tool to convert python indentation from spaces to tabs?

pythonindentation

提问by Corey

I have a some .py files that use spaces for indentation, and I'd like to convert them to tabs.

我有一些使用空格进行缩进的 .py 文件,我想将它们转换为制表符。

I could easily hack together something using regexes, but I can think of several edge cases where this approach could fail. Is there a tool that does this by parsing the file and determining the indentation level the same way the python interpreter does?

我可以使用正则表达式轻松地将某些东西组合在一起,但我可以想到这种方法可能会失败的几种边缘情况。是否有一种工具可以通过解析文件并以与 python 解释器相同的方式确定缩进级别来执行此操作?

回答by wimh

If there are not many files to convert, you can open them in vim, and use the :retabcommand.

如果要转换的文件不多,可以在vim 中打开,使用:retab命令。

See the vim documentationfor more information.

有关更多信息,请参阅vim 文档

回答by Greg

Python includes a script for the opposite (tabs to spaces). It's C:\Python24\Tools\Scripts\reindent.pyfor me

Python 包含一个相反的脚本(制表符到空格)。这是C:\Python24\Tools\Scripts\reindent.py给我的

回答by Orjanp

:retab will swap tab with spaces, and :retab! will swap spaces with tab. 1 tab = 4 spaces, 4 spaces = 1 tab, depending on your tab setting.

:retab 将用空格交换制表符,而 :retab! 将与制表符交换空格。1 个制表符 = 4 个空格,4 个空格 = 1 个制表符,具体取决于您的制表符设置。

回答by mzuther

If you use Linux, you might also play around with unexpand:

如果您使用 Linux,您也可以使用unexpand

Convert blanks in each FILE to tabs, writing to standard output. With no FILE, or when FILE is -, read standard input.

将每个 FILE 中的空白转换为制表符,写入标准输出。没有 FILE 或 FILE 为 - 时,读取标准输入。

回答by Alastair

In emacs, M-x tabifywill convert spaces to tabs where possible. You'll probably want to set the tab-widthvariable appropriately.

在 emacs 中,M-x tabify将尽可能将空格转换为制表符。您可能希望tab-width适当地设置变量。

I don't know if this addresses your concern that spaces be interpreted in the same way as the python interpreter, but you could always load up python-mode and use M-x indent-region.

我不知道这是否解决了您对空格的解释方式与 python 解释器相同的担忧,但您始终可以加载 python-mode 并使用M-x indent-region.