Python 2 到 Python 3 的迁移指南
1. Python 2 与 Python 3 的核心差异概述
Python 3 是一种较为简洁的语言,从 Python 2 迁移到 Python 3 的过程并非极其困难。不过,许多常见的第三方包尚未完成迁移。如果你的应用依赖于不兼容的库,可能需要暂缓升级,或者贡献自己的专业知识来助力迁移。
要了解 Python 3 的开发和迁移过程的概述,可阅读 PEP3000(http://www.python.org/dev/peps/pep - 3000/)。
2. 主要语言变化
2.1 print 成为函数
在 Python 之前的版本中,print 是一个语句,不需要括号,也不能将其作为一等对象传递。而在 Python 3 中,print 变成了函数。
以下是 Python 2 的有效代码:
Python 2.6.1 (r261:67515, Feb 11 2010, 00:51:29)
[GCC 4.2.1 (Apple Inc. build 5646)] on darwin
Type "help", "copyright", "credits", or "license" for more information.
>>> f = open('outfile', 'w')
>>> print >>f, "The Output"
>>>
在 Python 3 中运行上述代码会导致异