Python Start HTTP Server In Code (Create .py To Start HTTP Server)
The following script would do the same for either Python 2 or 3:
try:
# Python 2
from SimpleHTTPServer import test, SimpleHTTPRequestHandler
except ImportError:
# Python 3
from http.server import test, SimpleHTTPRequestHandler
test(SimpleHTTPRequestHandler)
This runs the exact same callable that is used when you run the module from the command line with the -m
switch.
The Python 3 version includes command-line support to determine what interface and port to bind to, but your command line doesn't make use of this anyway.
The accepted answer is not work for me. If it's not working for you too, please try this.
from http.server import HTTPServer, SimpleHTTPRequestHandler
httpd = HTTPServer(('localhost', 8000), SimpleHTTPRequestHandler)
httpd.serve_forever()