[实验]从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。

欢迎加入QQ群-->: 979659372 Python中文网_新手群

推荐PyPI第三方库


热门话题
使用Selenium Java查找筛选器窗格“铅笔图标”的元素时出现问题   分布式缓存l2上使用infinispan和hibernate的java连接锁   使用Java的DOM XML API解析XML中的符号和   java是解析和操作字符串的有效方法   java发布NewRelicMeterRegistry时如何过滤仪表   多维数组在java中读取文件后将数据值分组   java如何将httpClient配置为jsoup   java BreakIterator在Android中是如何工作的?   找不到maven GAE类:原因:java。lang.ClassNotFoundException应用程序标识cRedential$AppenginecRedential包装   Jlabel调整java大小   调试如何在VScode中的java类依赖项中设置断点   java正在获取文件夹名,而不是。mp3文件{Android}   java如何将从DiffieHellman类生成的AES密钥添加到使用该密钥的类