如何修复 Python 缩进 [英] How to fix Python indentation

查看:80
本文介绍了如何修复 Python 缩进的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一些缩进不一致的 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.

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

How can I fix the indentation (like HTML Tidy, but for Python) without breaking the code?

推荐答案

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

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

更改要使用的 Python (.py) 文件4 个空格缩进,没有硬制表符人物.还要修剪多余的空间和来自行尾的制表符,以及删除末尾的空行文件.还要确保最后一行结束换行.

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.

注意:如果你的 Linux 发行版没有默认安装 Python 的 reindent:

NOTE: If your linux distro does not have reindent installed by default with Python:

许多 linux 发行版默认没有安装 reindentpython -->获得 reindent 的一种简单方法是执行 pip install 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.

附言pip 的替代方法是使用您的发行版包管理器(即 apt-getyumdnf)但是那么你需要弄清楚哪个包有命令行工具,因为每个发行版在不同的包中都有这个工具.

p.s. An alternative to pip is to use your distros package manager (i.e. 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.

这篇关于如何修复 Python 缩进的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆