支持多个 Python 版本

页面状态

已废弃

上次审核时间

2014-12-24

FIXME

Useful projects/resources to reference:

- DONE six
- DONE python-future (http://python-future.org)
- tox
- DONE Travis and Shining Panda CI (Shining Panda no longer available)
- DONE Appveyor
- DONE Ned Batchelder's "What's in Which Python"
  - http://nedbatchelder.com/blog/201310/whats_in_which_python_3.html
    - http://nedbatchelder.com/blog/201109/whats_in_which_python.html
- Lennart Regebro's "Porting to Python 3"
- Greg Hewgill's script to identify the minimum version of Python
  required to run a particular script:
  https://github.com/ghewgill/pyqver
- the Python 3 porting how to in the main docs
- cross reference to the stable ABI discussion
  in the binary extensions topic (once that exists)
- mention version classifiers for distribution metadata

除了创建 Python 包所需的工作之外,通常还需要使包在不同版本的 Python 上可用。不同的 Python 版本可能包含不同的(或重命名的)标准库包,并且 Python 2.x 和 3.x 版本之间的变化包括语言语法的变化。

手动执行,确保包在所有目标 Python 版本(和操作系统!)上正常工作所需的所有测试可能非常耗时。幸运的是,有几种工具可以解决这个问题,这里将简要讨论这些工具。

自动化测试和持续集成

有几种用于自动化测试的托管服务。这些服务通常会监控您的源代码存储库(例如在 GitHubBitbucket),并在每次新提交时运行您的项目测试套件。

这些服务还提供在多个 Python 版本上运行项目测试套件的功能,提供关于代码是否能工作的快速反馈,而无需开发人员自己执行此类测试。

维基百科对许多持续集成系统进行了广泛的比较。当结合使用时,有两个托管服务可以在 Linux、Mac 和 Windows 上提供自动化测试

  • Travis CI 提供 Linux 和 macOS 环境。撰写本文时,Linux 环境是 Ubuntu 12.04 LTS Server Edition 64 位,而 macOS 是 10.9.2。

  • Appveyor 提供 Windows 环境(Windows Server 2012)。

TODO Either link to or provide example .yml files for these two
services.

TODO How do we keep the Travis Linux and macOS versions up-to-date in this
document?

Travis CIAppveyor 都需要一个 YAML 格式的文件作为测试指令的规范。如果任何测试失败,可以检查该特定配置的输出日志。

对于旨在通过单一源策略在 Python 2 和 3 上部署的 Python 项目,有多种选择。

单一源 Python 包的工具

six 是 Benjamin Peterson 开发的一个工具,用于封装 Python 2 和 Python 3 之间的差异。six 包已得到广泛使用,可以被视为编写可在 Python 2 和 3 中使用的单一源 Python 模块的可靠方法。six 模块最早可用于 Python 2.5。一个名为 modernize 的工具,由 Armin Ronacher 开发,可用于自动应用 six 提供的代码修改。

类似于 sixpython-future 是一个包,它在 Python 2 和 Python 3 源代码之间提供了一个兼容层;然而,与 six 不同,这个包旨在通过与两个 Python 版本之一匹配的语言语法在 Python 2 和 Python 3 之间提供互操作性:可以使用

  • 在 Python 3 项目中使用 Python 2(按语法)模块。

  • Python 2项目中使用 Python 3(按语法)模块。

由于其双向性,python-future 提供了一条将 Python 2 包逐模块转换为 Python 3 语法的途径。然而,与 six 相比,python-future 仅支持 Python 2.6 及更高版本。类似于 sixmodernizepython-future 附带了两个脚本,名为 futurizepasteurize,可以分别应用于 Python 2 模块或 Python 3 模块。

使用 sixpython-future 会为您的包添加一个额外的运行时依赖项:对于 python-future,可以使用 --stage1 选项调用 futurize 脚本,仅应用 Python 2.6+ 已经提供的向前兼容 Python 3 的更改。任何剩余的兼容性问题将需要手动更改。

哪个 Python 中有什么?

Ned Batchelder 提供了一份每个 Python 版本中更改的列表,适用于 Python 2Python 3.0-3.3Python 3.4-3.6。这些列表可用于检查 Python 版本之间的任何更改是否可能影响您的包。

TODO These lists should be reproduced here (with permission).

TODO The py3 list should be updated to include 3.4