使 python 代码与 2.7 和 3.6+ 版本兼容 - 关于 Queue 模块

Making python code compatible for working with 2.7 and 3.6+ versions- regarding Queue module

我想使我的一些通用代码在 python2.7python3.6 版本中工作。 在语法方式中,它仅暗示以下内容:将打印转换为类型的控制台:print "hello"print("hello") 这在两个版本中都是可接受的。

该问题仅在 Queue 模块的一个模块导入中出现。
在 Python2.7 中:from Queue import Queue
在 Python3.6 中:from queue import Queue

尝试在 import 部分做一些事情,例如:

try:  
    from Queue import Queue
except ImportError:
    from queue import Queue

可行,但它确实不优雅和丑陋,有什么想法可以使它更合理吗?

可能是以下:

import platform
if platform.python_version().startswith('2.7'):  
    from Queue import Queue
elif platform.python_version().startswith('3.6'):
    from queue import Queue

这实际上并不是什么坏习惯,可以在很多 python 模块中看到。当涉及到同时支持 Python2 和 Python3 时,six 模块会非常方便。

有了六个,您就可以像那样导入队列。

from six.moves import queue

它会根据 Python 版本自动将您的导入代理到适当的位置。