Python 3:AttributeError:'module'对象在终端中使用urllib没有属性'__path__'
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/30261860/
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
Python 3: AttributeError: 'module' object has no attribute '__path__' using urllib in terminal
提问by Przemek
My code is runnning perfectly in PyCharm, but I have error messages while trying to open it in terminal. What's wrong with my code, or where I made mistakes?
我的代码在 PyCharm 中完美运行,但是在尝试在终端中打开它时出现错误消息。我的代码有什么问题,或者我哪里出错了?
import urllib.request
with urllib.request.urlopen('http://python.org/') as response:
html = response.read()
print(html)
Output from terminal:
终端输出:
λ python Desktop\url1.py
Traceback (most recent call last):
File "<frozen importlib._bootstrap>", line 2218, in _find_and_load_unlocked
AttributeError: 'module' object has no attribute '__path__'
During handling of the above exception, another exception occurred:
Traceback (most recent call last):
File "Desktop\url1.py", line 1, in <module>
import urllib.request
File "C:\Users\Przemek\Desktop\urllib.py", line 1, in <module>
import urllib.request
ImportError: No module named 'urllib.request'; 'urllib' is not a package
采纳答案by Padraic Cunningham
You called a file C:\Users\Przemek\Desktop\urllib.py
, you need to rename it. You are importing from that not the actual module. rename C:\Users\Przemek\Desktop\urllib.py
and remove any C:\Users\Przemek\Desktop\urllib.pyc
.
你调用了一个文件C:\Users\Przemek\Desktop\urllib.py
,你需要重命名它。你是从那个导入而不是实际的模块。重命名C:\Users\Przemek\Desktop\urllib.py
并删除任何C:\Users\Przemek\Desktop\urllib.pyc
.
It is not the file you are running but you have the file in the same directory so python checks the current directory first hence the error.
它不是您正在运行的文件,而是您在同一目录中拥有该文件,因此 python 首先检查当前目录,因此出现错误。
回答by James Mills
You sare shadowing the standard library package urllib
by naming your source file urllib.py
. Rename it!
您可以urllib
通过命名源文件来隐藏标准库包urllib.py
。重命名!
The fact this works at all in Pycharm is an amazing feat of engineering on the PyCharm developers!
这在 Pycharm 中完全有效的事实是 PyCharm 开发人员的一项惊人的工程壮举!
You can also use absolute imports (from __future__ import absolute_import
) here; but in this case I don't think it'll help since your startup source name shadows the very library/package you are trying to use!
您也可以from __future__ import absolute_import
在此处使用绝对导入 ( );但在这种情况下,我认为它不会有帮助,因为您的启动源名称会影响您尝试使用的库/包!
回答by Iron Fist
Also, this:
还有这个:
import urllib.request
with urllib.request.urlopen('http://python.org/') as response:
Should be like this:
应该是这样的:
import urllib
with urllib.urlopen('http://python.org/') as response: