python3代码兼容python2的方式
1.使用future特性
Python的每个新版本都会增加一些新的功能,或者对原来的功能作一些改动。有些改动是不兼容旧版本的,也就是在当前版本运行正常的代码,到下一个版本运行就可能不正常了。
Python提供了__future__模块,把下一个新版本的特性导入到当前版本,于是我们就可以在当前版本中测试一些新版本的特性。
例如在python2.7中使用python3的print(“xxx”),就需要在文件开头引用future模块,不然报错:
SyntaxError: from __future__ imports must occur at the beginning of the file
#使用高版本的print与除法
from __future__ import print_function
from __future__ import division
Python 2.7.12 (default, Nov 12 2018, 14:36:49)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import __future__
>>> print 'aaa'
aaa
>>> print(aa)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: nam