V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
推荐学习书目
Learn Python the Hard Way
Python Sites
PyPI - Python Package Index
http://diveintopython.org/toc/index.html
Pocoo
值得关注的项目
PyPy
Celery
Jinja2
Read the Docs
gevent
pyenv
virtualenv
Stackless Python
Beautiful Soup
结巴中文分词
Green Unicorn
Sentry
Shovel
Pyflakes
pytest
Python 编程
pep8 Checker
Styles
PEP 8
Google Python Style Guide
Code Style from The Hitchhiker's Guide
kidlj
V2EX  ›  Python

既然 Python 2 和 Python 3 不兼容,很多 Pypi 包是如何做到既可用于 Python 2,又可用于 Python 3 的?

  •  
  •   kidlj ·
    kidlj · 2015-01-12 16:12:24 +08:00 · 3388 次点击
    这是一个创建于 3385 天前的主题,其中的信息可能已经有所发展或是发生改变。
    7 条回复    2015-01-12 19:03:56 +08:00
    jiang42
        1
    jiang42  
       2015-01-12 16:12:42 +08:00   ❤️ 1
    six
    Muninn
        2
    Muninn  
       2015-01-12 16:13:23 +08:00   ❤️ 1
    关键代码写判断呗。。。

    有的是用six之类的转换,但是不靠谱。。。
    zhicheng
        3
    zhicheng  
       2015-01-12 16:15:25 +08:00   ❤️ 1
    因为可以 import __future__
    geeklian
        4
    geeklian  
       2015-01-12 16:36:58 +08:00 via iPhone   ❤️ 1
    也不是完全不兼容,很多库只是名字的区别,甚至就是大小写区别。if version《3:import XXX as xxx else :import xxx
    whtsky
        5
    whtsky  
       2015-01-12 18:05:33 +08:00   ❤️ 1
    from __future__ import xxx

    try:
    except:

    sys.version_info
    anjunecha
        6
    anjunecha  
       2015-01-12 18:15:08 +08:00   ❤️ 1
    这是官方关于 __future__ 的文档 https://docs.python.org/2.7/library/__future__.html
    zhyu
        7
    zhyu  
       2015-01-12 19:03:56 +08:00
    建议看看这个 How to write forwards compatible Python code: http://lucumr.pocoo.org/2011/1/22/forwards-compatible-python/
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   2285 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 25ms · UTC 00:55 · PVG 08:55 · LAX 17:55 · JFK 20:55
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.