Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

http

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?

like image 386
ducsuus Avatar asked Jul 04 '14 20:07

ducsuus


People also ask

How do I start an HTTP server?

Installing HTTP server using NPM Run the command line/terminal on your system (it doesn't matter which directory you are currently in). Execute npm install -g http-server . Once NPM finishes, you have the tiny HTTP-server installed. That's it.

How does HTTP server work in Python?

HTTP Web Server is simply a process which runs on a machine and listens for incoming HTTP Requests by a specific IP and Port number, and then sends back a response for the request. <p>Congratulations! The HTTP Server is working!


2 Answers

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.

like image 74
Martijn Pieters Avatar answered Sep 17 '22 17:09

Martijn Pieters


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()
like image 40
Trieu Nguyen Avatar answered Sep 20 '22 17:09

Trieu Nguyen