跳转到主要内容

[实验性] 在Python 3中运行Python 2代码

项目描述

past 是一个帮助Python 2/3兼容性的包。与 future 包包含Python 3构造函数的向后移植不同,past 提供了Python 3中一些Python 2构造函数的实现。它旨在少量使用,作为在正确移植之前从Python 3运行旧Python 2代码的一种方式。

库的潜在用途

  • 在将Python 2代码库移植到Python 3的步骤中(例如,使用 futurize 脚本)

  • 为具有与Python 2相同的API的先前仅Python 2库提供Python 3支持,特别是关于8位字符串(past.builtins.str 类型)。

  • 帮助为使用尚未升级其代码以适应Python 3或希望逐步升级到Python 3样式的库的应用程序提供最小努力的Python 3支持。

要安装 past,请使用

$ pip install future

以下是一些在Python 3和2上运行相同的示例

>>> from past.builtins import (str as oldstr, range, reduce,
                               raw_input, xrange)

>>> philosopher = oldstr(u'孔子'.encode('utf-8'))
>>> # This now behaves like a Py2 byte-string on both Py2 and Py3.
>>> # For example, indexing returns a Python 2-like string object, not
>>> # an integer:
>>> philosopher[0]
'å'
>>> type(philosopher[0])
<past.builtins.oldstr>

>>> # The div() function behaves like Python 2's / operator
>>> # without "from __future__ import division"
>>> from past.utils import div
>>> div(3, 2)    # like 3/2 in Py2
0
>>> div(3, 2.0)  # like 3/2.0 in Py2
1.5

>>> # List-producing versions of range, reduce, map, filter
>>> from past.builtins import range, reduce
>>> range(10)
[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
>>> reduce(lambda x, y: x+y, [1, 2, 3, 4, 5])
15

>>> # Other functions removed in Python 3 are resurrected ...
>>> from past.builtins import execfile
>>> execfile('myfile.py')

>>> from past.builtins import raw_input
>>> name = raw_input('What is your name? ')
What is your name? [cursor]

>>> from past.builtins import reload
>>> reload(mymodule)   # equivalent to imp.reload(mymodule) in Python 3

>>> from past.builtins import xrange
>>> for i in xrange(10):
...     pass

它还提供了实验性的导入钩子,因此您可以从Python 3导入并运行Python 2模块

>>> from past import autotranslate
>>> autotranslate('mypy2module')

>>> import mypy2module

文档

请参阅 http://python-future.org.

鸣谢

作者

Ed Schofield

赞助商

澳大利亚Python Charmers Pty Ltd: http://pythoncharmers.com

许可

版权所有 2013-2014 澳大利亚Python Charmers Pty Ltd。软件在MIT许可下分发。请参阅LICENSE.txt。

项目详情


支持者