6

I am trying to setup http server on my machine but I get the error:

ModuleNotFoundError: No module named 'http.server'; 'http' is not a package

I have 2 files in my project directory: http.py and index.html.

Here is the http.py:

import http.server
import socketserver

PORT = 8080
Handler = http.server.SimpleHTTPRequestHandler

with socketserver.TCPServer(("", PORT), Handler) as httpd:
    print("serving at port", PORT)
    httpd.serve_forever()

I have already tried changing module to BaseHTTPServer and I get this error:

ModuleNotFoundError: No module named 'BaseHTTPServer'

I also notice a weird thing happen on my terminal. If I try do

python3 -m pip uninstall <module>

I get an error such as

ModuleNotFoundError: No module named 'http.server'; 'http' is not a package

which is throwing me off because I am not even running the file. I mention this in case it is any indication that some local configuration might be the problem of all.

Azeem
  • 11,148
  • 4
  • 27
  • 40
Luis0001
  • 93
  • 1
  • 1
  • 5
  • I can run the above code in a script. How are you interacting with the snippet shared above? [http](https://docs.python.org/3.8/library/http.server.html) is part of the standard library so you can't `pip` uninstall it. – Brayoni Apr 28 '20 at 19:24
  • Hi, thanks for the reply. I have 2 files in dir > http.py and index.html. Curiously I was able to make it work one way but not by running my main file. I can make it work by doing ```python3``` to enter py and do it line by line but I have to import http first or else I get the attribute error. However I tried to do ```import http import http.server``` in my main py file but it still gives me the attr error. – Luis0001 Apr 28 '20 at 21:21
  • The fact that your file is called `http.py` is the problem. – Karl Knechtel Apr 29 '20 at 05:02
  • This is an important detail that should be part of the question: **I have 2 files in dir > http.py and index.html**. Consider sharing the error stack trace as well. – Brayoni Apr 29 '20 at 05:03
  • @chx if you found [the answer](https://stackoverflow.com/a/61494575/7695722) useful, kindly accept it. Thanks. – Brayoni Apr 29 '20 at 17:33
  • this fixed it. Thank you!! – Luis0001 Apr 30 '20 at 03:04

1 Answers1

19

You have named your file as http.py. This is overriding the standard library http module. To solve:

  • You have to rename the file http.py to something else.
  • Remove .pyc files in the project

    find . -name "*.pyc" -delete

  • Run the program again.

It may interest you to read up on how modules and packages work in Python.

Brayoni
  • 696
  • 7
  • 14