zoukankan      html  css  js  c++  java
  • python(内置函数, 模块)打补丁 兼容py2 py3

    转自

    不止于python

    使用背景

      py2官方已不在维护, 所以将项目升级到py3, 但是项目也不是一行两行的事, 并且项目还在使用, 所以必须要兼容py2, 升级到py3

      所以就有了以下常见问题, 比如, py2的内置函数py3已不使用, py2的内置模块py3已经改名.........

     

    错误文件测试

    print(unicode, type(unicode))
    #  输出
    """
    Traceback (most recent call last):
      File "/Users/msw/Desktop/tools/py3_test.py", line 4, in <module>
        print(unicode, type(unicode))
    NameError: name 'unicode' is not defined
    """

    解决方案

    打补丁

     (下列补丁中的判断py版本是为了兼容2,3)

      1. 内置函数补丁

    import sys
    if sys.version_info[0] >= 3:
        PY3 = True
    else:
        PY3 = False
    
    
    def patch_default_type():
        if not PY3:
            return
        __builtins__["unicode"] = __builtins__["basestring"] = str
        __builtins__["long"] = int

     导入补丁 测试

    from py2_to_py3 import patch_default_type
    patch_default_type()
    
    print(unicode, type(unicode))
    
    # py3 输出 <class 'str'> <class 'type'>
    # py2 输出 (<type 'unicode'>, <type 'type'>)

     2. 内置模块补丁

    import sys
    if sys.version_info[0] >= 3:
        PY3 = True
    else:
        PY3 = False
    
    def patch_modules(copy_reg=False, itertools_imap=False):
        if not PY3:
            return
       if copy_reg: import copyreg sys.modules["copy_reg"] = copyreg if itertools_imap: import itertools setattr(itertools, "imap", map)

     导入补丁 测试

    from py2_to_py3 import patch_modules
    patch_modules(copy_reg=True, itertools_imap=True)
    
    import copy_reg
    from itertools import imap
    
    
    print(copy_reg)
    print(imap)
    # py3 输出 # <module 'copyreg' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/copyreg.py'> # <class 'map'> # py2 输出 # <module 'copy_reg' from '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.pyc'> # <type 'itertools.imap'>

    补丁模块

    主要用于兼容py2 py3, 功能强大, 使用简单

    six

    from six.moves import map, copyreg
    
    print(copyreg)
    print(map)
    
    # py3 输出
    # <module 'copyreg' from '/Library/Frameworks/Python.framework/Versions/3.6/lib/python3.6/copyreg.py'>
    # <class 'map'>
    
    # py2 输出
    # <module 'copy_reg' from '/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/copy_reg.pyc'>
    # <type 'itertools.imap'>

    six基本可以解决兼容py2,3 问题, 但还有极个别的问题, 需要单独处理

  • 相关阅读:
    textRNN & textCNN的网络结构与代码实现!
    四步理解GloVe!(附代码实现)
    NLP系列文章:子词嵌入(fastText)的理解!(附代码)
    自然语言处理(NLP)的一般处理流程!
    强化学习(Reinforcement Learning)中的Q-Learning、DQN,面试看这篇就够了!
    迁移学习(Transfer),面试看这些就够了!(附代码)
    白话--长短期记忆(LSTM)的几个步骤,附代码!
    三步理解--门控循环单元(GRU),TensorFlow实现
    Django框架1——视图和URL配置
    os模块
  • 原文地址:https://www.cnblogs.com/mswei/p/13970404.html
Copyright © 2011-2022 走看看