Python 3.3 - urllib.request - 导入错误

时间:2013-04-04 20:52:25

标签: python urllib pycharm python-3.3

当我尝试在PyCharm 2.7中的OS X 10.8上运行以下Python 3.3代码(或使用Python 3.3 / 2.7.3启动程序运行.py文件)时:

import urllib.request
f = urllib.request.urlopen('http://www.python.org/')
print(f.read(300))

我收到以下错误消息:

/System/Library/Frameworks/Python.framework/Versions/3.3/bin/python3 /Users/username/PycharmProjects/urllib/urllib.py
Traceback (most recent call last):
  File "<frozen importlib._bootstrap>", line 1512, 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 "/Users/username/PycharmProjects/urllib/urllib.py", line 3, in <module>
    import urllib.request
  File "/Users/username/PycharmProjects/urllib/urllib.py", line 3, in <module>
    import urllib.request
ImportError: No module named 'urllib.request'; urllib is not a package

Process finished with exit code 1

我能成功运行代码的唯一方法是通过Python shell。

关于如何解决这个问题的任何想法?

感谢。


我将文件名更改为url.py,现在它在PyCharm中成功执行。

但是当通过Python Launcher 3.3执行文件时,它给出了以下错误:

 File "/Users/username/PycharmProjects/urllib/url.py", line 3, in <module>
import urllib.request
ImportError: No module named request

为什么PyCharm(3.3)中的代码运行正常但是在使用Python Launcher(3.3)启动时给出了错误?

3 个答案:

答案 0 :(得分:11)

您将文件命名为urllib,它正在影响标准库包。重命名您的文件。

答案 1 :(得分:2)

在Mac中,VSCode使用的是Python2。如果打印urllib模块,您将发现该模块适用于Python 2。

因此,我添加了一条注释以选择Python版本:

#!/usr/local/bin/python3
from urllib.request import urlopen

答案 2 :(得分:0)

就我而言,它解决了在命令面板(shift + commant + p)中激活的问题。 Linting:启用Linting:打开,然后在VMStudio设置(首选项=>设置)中,在Python:linter中选择flake8 =>短绒用作flake8。