zoukankan      html  css  js  c++  java
  • 融合python2和python3

    很多情况下你可能会想要开发一个程序能同时在python2和python3中运行。

    想象一下你开发了一个模块,成百上千的人都在使用它,但不是所有的用户都同时使用python 2和3。这种情况下你有两个选择。第一种情况,你可以讲2种模块分开,分别为python2和python3开发一个。另一种情况就是,你可以修改你现有的代码,使其同时支持python2和python3。

    今天我们来讲一些方法使你的代码能同时兼容它们。

    Future import

    首先,也是最重要的的方法即是__future__模块的导入。它使你能在python2中引入python3的功能模块。下面举例说明:

    上下文管理器是python2.6+中的新特新,假如你要在python2.5中使用它:

    from __future__ import with_statement
    

    python2中的print语法在python3中变成了print()函数,如果你想要在python2中使用print()函数,你可以从__future__模块中引入它:

    print
    # Output:
    
    from __future__ import print_function
    print(print)
    # Output: <built-in function print>
    

     解决模块重命名:

    首先,告诉我在你的代码中你是怎样引入包的呢?大部分应该是这样的:

    import foo
    # or
    from foo import bar
    

     那你是否有尝试过,其实你可以这样做:

    import foo as foo
    

     其实这两者的效果是一样的,但是要使你的代码兼容python2和python3这是至关重要的,因为你可以这样做:

    try:
        import urllib.request as urllib_request  # for Python 3
    except ImportError:
        import urllib2 as urllib_request  # for Python 2
    

     所以让我来解释一下上面的代码,我们使用try/except语句包住了我们的引入代码。我们这么做是因为在python2中没有urllib.request模块所以它会产生一个ImportError。其中python3中的urllib.request模块的内容和python2中的urllib2是一样的。所以通过以上代码在python3中我们会引入urllib.request而在python2中我们会引入urllib2,而且都是通过别名urllib_request调用。

    一些废弃的python2内置

    另外一些要记住的就是,在python3中已经移除的12中python2中的内置功能。切记不要在python2中使用它们如果你要你的python2代码同时兼容python3的话。下面这个方法能强制你不能使用这12个废弃的方法:

    from future.builtins.disabled import *
    

     现在,无论何时你想要使用这些废弃的模块,都会引起NameError错误:

    from future.builtins.disabled import *
    
    apply()
    # Output: NameError: obsolete Python 2 builtin apply is disabled
    

    非标准库的安装

    这有一些第三方的库让你在python2中可以使用python3的方法:

    • enum pip install enum34
    • singledispatch pip install singledispatch
    • pathlib pip install pathlib

    进一步阅读,在python文档 comprehensive guide中有更加详细的说明使你的代码能同时兼容python2和python3。

    原文地址:http://book.pythontips.com/en/latest/targeting_python_2_3.html

    欢迎多来访问博客:http://liqiongyu.com/blog

    微信公众号:

  • 相关阅读:
    Python 基础
    Python 基础
    Python 基础
    Python 基础
    Python 基础
    Python 基础
    Python 基础
    Python 基础
    Python 基础
    Python 基础
  • 原文地址:https://www.cnblogs.com/Liqiongyu/p/5948463.html
Copyright © 2011-2022 走看看