Python 3: AttributeError: 'module' object has no attribute '__path__' using urllib in terminal
Asked Answered
P

3

12

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?

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
Parthenogenesis answered 15/5, 2015 at 14:20 Comment(3)
import urllib.request is valid ??? – Joiejoin
@VivekSable, yes for python3. – Astilbe
My problem was that I was trying to run a file using python -m thing.py instead of python thing.py πŸ™ˆ – Dannica
A
13

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.

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.

Astilbe answered 15/5, 2015 at 14:20 Comment(2)
Yes, that's it, I had a file named urllib.py in same directory. Thanks for your help! – Parthenogenesis
@Przemek. no prob, happens pretty often – Astilbe
M
1

You sare shadowing the standard library package urllib by naming your source file urllib.py. Rename it!

The fact this works at all in Pycharm is an amazing feat of engineering on the PyCharm developers!

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!

Muscovado answered 15/5, 2015 at 14:23 Comment(0)
J
-1

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:
Jobie answered 15/5, 2015 at 14:29 Comment(2)
Not really, the OP is using python3. – Astilbe
My Bad, thought 2.7!! – Jobie

© 2022 - 2024 β€” McMap. All rights reserved.