【脚本语言系列】关于Python基础知识兼容Python 2.x+Python 3.x,你需要知道的事

如何兼容Python 2.x+Python 3.x

  • 保留字变函数
    Python 2.x使用__future__模块使用Python 3.x中的函数
# -*- coding:utf-8 -*-
# For Python 2.x
print print
  File "<ipython-input-13-8fe752f7a342>", line 3
    print print
              ^
SyntaxError: invalid syntax
# -*- coding:utf-8 -*-
# For Python 2.x & Python 3.x
from __future__ import print_function

print(print)
<built-in function print>
  • 模块更名
    使用try/except模块处理Python 2.xPython 3.x不同名的模块
# -*- coding:utf-8 -*-
# For Python 2.x & Python 3.x
try:
    import urllib.request as urllib_request # For Python 3.x
except ImportError:
    import urllib2 as urllib_request # For Python 2.x
  • 模块/功能过时
    使用future模块禁用Python 2.x可用但Python 3.x过时的模块
# -*- coding:utf-8 -*-
# For Python 2.x & Python 3.x
from future.builtins.disabled import *

apply()
---------------------------------------------------------------------------

NameError                                 Traceback (most recent call last)

<ipython-input-15-99a87af09d54> in <module>()
      3 from future.builtins.disabled import *
      4 
----> 5 apply()


c:\python27\lib\site-packages\future\builtins\disabled.pyc in disabled(*args, **kwargs)
     55         no longer a builtin in Python 3.
     56         '''
---> 57         raise NameError('obsolete Python 2 builtin {0} is disabled'.format(name))
     58     return disabled
     59 


NameError: obsolete Python 2 builtin apply is disabled

什么是兼容Python 2.x+Python 3.x

常用的兼容Python2.x和Python3.x的方式是:
* 开发2个模块,分别针对Python 2.x和针对_ Python 3.x_
* 使用兼容模块,用于兼容Python 2.xPython 3.x

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值