"为使Python代码能兼容2.7与3.6+版本- 关于Queue模块的问题"

2024-04-25 21:36:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想让我的一些通用代码通过python2.7和{}版本工作。 在语法方式上,它只意味着以下几点:将打印转换为类型的控制台:print "hello"到{},这两个版本都可以接受。在

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

正在尝试在import部分中执行以下操作:

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

会工作但它真的不雅观难看,有什么办法让它更合理?在


Tags: 模块代码fromimport版本类型hello队列
2条回答

可能是下面的:

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模块非常方便。在

有了6个,就可以像这样导入队列了。在

from six.moves import queue

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

相关问题 更多 >

    热门问题