使 Python 2 与 Python 3 兼容

Make Python 2 compatible with Python 3

我目前的要求是在 Python 2.4.3 中编写脚本,该脚本与 RHEL 5 捆绑在一起。但是几年后,比如说 5 年,服务器可能会升级到 Python 3 附带的 RHEL 8 或 9。所以我应该编写与这两个版本兼容的代码。现在我的脚本包含基本操作,例如创建目录、解压缩文件、文件操作、XML 文件读取(我现在正在使用 minidom 执行)和一些散列。

现在我发现一个名为 python-modernize 的工具可以完成构建在 2to3 之上的工作。我搜索了该工具,但得到了一个 tar.gz 文件。它不包含 python-modernize 文件,正如他们在其用法中所说的那样。但我找到的只是一个 setup.py 文件。我是 Python 的新手,我所知道的是 pip 已经完成了一些事情。但我也读到,使用 pip 对 Python 2.4.3 来说是一项艰巨的工作。

请告诉我怎样才能完成这项工作。

我也提到了 this 但找不到如何使用该工具。

此外,如果有任何好的替代方案,请告诉我。

使用来自 Benjamin Peterson 的 six 库。

它是专门为这个用例设计的。 通过从六个库中导入不同于 2 到 3 的内容,它允许您拥有一个同时支持 Python 2 和 Python 3 的代码库。

只需导入它并使用它的定义即可:

import six

示例:

from six import u, b

以上是经典,其中 Python 3+ 对 Unicode 字符串和字节的工作方式进行了更严格的更改。

Six is a Python 2 and 3 compatibility library. It provides utility functions for smoothing over the differences between the Python versions with the goal of writing Python code that is compatible on both Python versions. See the documentation for more information on what is provided.

Six supports every Python version since 2.5. It is contained in only one Python file, so it can be easily copied into your project. (The copyright and license notice must be retained.)

更新: 对不起,我错过了那里的 Python<=2.5 要求;但老实说,我认为使用六个是你​​最好的选择。您必须说服您 拥有 的权力至少使用 Python 2.5.

更新 #2: 我最强烈的建议是至少将您的代码升级到 Python 2.7。不要落后,否则你将永远落后于球!

更新 #3: 根据以上非常有用的评论;我同意。只需使用您现在拥有的东西即可。 5年确实是很长的时间,到那时可能不会有同样的限制!