[实验]从python 3运行python 2代码
past的Python项目详细描述
past是一个帮助实现python 2/3兼容性的包。鉴于future 包含python 3构造到python 2的后端口,past提供 python 3中一些python 2结构的实现。它的目的是 作为从Python3运行旧Python2代码直到 端口正确。
库的潜在用途:
- 作为将Python2代码基移植到Python3的步骤(例如,使用futurizescript)
- 使用 与Python2上的API相同——特别是关于8位字符串(即 past.builtins.str类型)。
- 为了帮助为使用 还不希望将代码正确升级到python 3的库,或者 希望逐步升级到python 3风格。
要安装past,请使用:
$ pip install future
下面是一些在Python3和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
学分
Author: | Ed Schofield |
---|---|
Sponsor: | Python Charmers Pty Ltd, Australia: http://pythoncharmers.com |
许可
版权所有2013-2014 Python Charmers Pty Ltd,澳大利亚。 该软件是根据麻省理工学院的许可证发行的。请参阅license.txt。