Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Import http.client encouter import error with Python 3.4.1

I am following the example from the python online document(21.12.3) for practice. When I try to run my script with Run Module(F5), I always get an import error. But if I type them directly into IDLE command line, python does not complain. I am not sure what am I doing wrong.

The python version I am using is Python 3.4.1 (v3.4.1:c0e311e010fc, May 18 2014, 10:38:22) [MSC v.1600 32 bit (Intel)] on win32

The script is

import http.client

conn = http.client.HTTPConnection("192.168.1.2", 8080)
conn.request("GET", "/index.html")
r1 = conn.getresponse()
print(r1.status, r1.reason)
conn.close()

The error message is

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 "D:\User\Downloads\http.py", line 1, in <module>
    import http.client
  File "D:\User\Downloads\http.py", line 1, in <module>
    import http.client
ImportError: No module named 'http.client'; 'http' is not a package
like image 615
SSC Avatar asked Jul 22 '14 06:07

SSC


2 Answers

You probably have created a Python script and named it http.py in local directory. This conflicts with Python 3's builtin module with the same name and leads to this error. Quick solution is to rename your file to something less generic to avoid conflict with Python builtin modules.

But if you insist, you can clear the name ambiguity by fully qualifying the local python module name using absolute imports:

from . import http

or less confusingly:

from . import http as myhttp

or

from .http import something

On Python 2, it is necessary to enable the absolute import feature at the very top of the importing module using a future statement before using this feature:

from __future__ import absolute_import
like image 80
zaadeh Avatar answered Nov 15 '22 21:11

zaadeh


I had the same problem. In my case, there was another file named http.py in the same folder. I just renamed it, problem solved.

like image 38
Adam Silva Avatar answered Nov 15 '22 20:11

Adam Silva