Skip to content
Advertisement

Python Start HTTP Server In Code (Create .py To Start HTTP Server)

Currently I and many others are using a Python HTTP server on several platforms (Windows, OS X and potentially Linux). We are using a Python HTTP server to test a JavaScript game.

Right now we are launching the Python HTTP server through the command line on each platform (CMD, Terminal, etc.). Although this works well, it is becoming a pain to use this method, it would be nice to have a simple script that starts the Python HTTP server up.

The script needs to work on all platforms, seeing as all platforms will have Python installed it makes sense to write the script in Python.

Currently we are using the following commands to start the server:

On python 3

python -m http.server

On python 2

python -m SimpleHTTPServer

How would I put one of these lines into Python code, which I could save as a .py and simply double click on to start the HTTP server?

Advertisement

Answer

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.

Advertisement