`from Six.moves import urllib` 在 Python 中有什么作用?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/34989206/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
What does `from six.moves import urllib` do in Python?
提问by Dims
I found the following line in Python code:
我在 Python 代码中发现了以下行:
from six.moves import urllib
Simultaneously, I can find urllib.pyanywhere. I found that there is a file six.pyin package root and it has class Module_six_moves_urllib(types.ModuleType):inside.
同时,我可以在urllib.py任何地方找到。我发现six.py包根目录中有一个文件,class Module_six_moves_urllib(types.ModuleType):里面有。
Is this it? How is this defined?
是这个吗?这是如何定义的?
UPDATE
更新
Sorry I am new to Python and the question is about Python syntax. I learned, that what is after importis Python file name without a pyextension. So, where is this file in this case?
抱歉,我是 Python 新手,问题是关于 Python 语法。我了解到,后面import是没有py扩展名的 Python 文件名。那么,在这种情况下,这个文件在哪里?
回答by karlson
sixis a package that helps in writing code that is compatible with both Python 2 and Python 3.
Six是一个帮助编写与 Python 2 和 Python 3 兼容的代码的包。
One of the problems developers face when writing code for Python2 and 3 is that the names of several modules from the standard library have changed, even though the functionality remains the same.
开发人员在为 Python2 和 3 编写代码时面临的问题之一是标准库中几个模块的名称发生了变化,即使功能保持不变。
The six.movesmodule provides those modules under a common name for both Python2 and 3 (mostly by providing the Python2 module under the name of the Python 3 module).
该six.moves模块以 Python2 和 3 的通用名称提供这些模块(主要是通过以 Python 3 模块的名称提供 Python2 模块)。
So your line
所以你的线
from six.moves import urllib
imports urllibwhen run with Python3 and imports a mixture of urllib, urllib2and urlparsewith Python2, mimicking the structure of Python3's urllib. See also here.
进口urllib时Python3和进口的混合运行urllib,urllib2并urlparse与Python2,模仿Python3的结构urllib。另请参见此处。
EDITto address the update of the question:
编辑以解决问题的更新:
TLDR; There is not necessarily a direct relation between the imported module urlliband a file on the filesystem in this case. The relevant file is exactly what six.__file__points to.
TLDR;urllib在这种情况下,导入的模块和文件系统上的文件之间不一定有直接关系。相关文件正是six.__file__指向的内容。
Third party modules are defined in a file/directory that is
listed in sys.path. Most of the time you can find the name of the file a module is imported from by inspecting the __file__attribute of the module in question, e.g. six.__file__. However with six.movesthings are not as simple, precisely because the exposed modules might not actually map one to one to actual Python modules but hacked versions of those.
第三方模块在 中列出的文件/目录中定义sys.path。大多数情况下,您可以通过检查__file__相关模块的属性(例如six.__file__. 然而six.moves事情并不那么简单,正是因为暴露的模块实际上可能不会一对一地映射到实际的 Python 模块,而是这些模块的黑客版本。

