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) 启动时出现错误?

4

3 回答 3

16

您命名了您的文件urllib,它隐藏了标准库包。重命名您的文件。

于 2013-04-04T20:54:21.560 回答
2

在 mac 中,VSCode 使用的是 Python 2。如果你打印urllib模块,你会发现这个模块是为 Python 2 准备的。

所以,我添加了一条评论来选择 Python 版本:

#!/usr/local/bin/python3
from urllib.request import urlopen
于 2020-04-05T12:38:35.283 回答
0

就我而言,它解决了在命令面板中激活 (shift+commant+p) Linting: E​​nable Linting : on并在 VMStudio Settings (Preferences => Settings) 中选择 flake8 in Python:linter => Linter 用作 flake8。

于 2020-06-07T17:26:31.633 回答