How to Create an Instant Python Web Server using only the Command Line and Python?

Do you need to share a file quickly, test some code, or share your latest CSS? You can spontaneously create a web server hosting all the content of any directory, using nothing but Python. Python has a one-line command instant server, no apache, no nginx, all python. The command is effortless.

To start an instant web server using only Python at command line first navigate to the directory containing your files. Then type the following:

###Python 2 use this
python -m SimpleHTTPServer
###Python 3 use the following
python -m http.server

The command publishes the current directory as a web server immediately. If you have an index.html file site visitors will see it; otherwise, the server can only list the directory contents. The SimpleHTTPServer default port is 8000. So, to access the web server go to the following address from your local browser: http://127.0.0.1:8000

To access the server from other machines on your network, you will need to know your IP and remember, without an index.htm or index.html file in the directory; a simple directory listing will show instead.

As visitors browse through the instant server, your terminal will update logging their interactions, information like GET and PUSH requests, 404 errors, IP addresses, dates, times.

If you already have something working on port 8000, you’ll need to specify an alternative port. Using another port also gives some level of obscurity to the web server if you’re hoping only to broadcast something to a specific individual. To do this specify a port number at the end of the command above, like so:

python -m SimpleHTTPServer 4104

Adding the port number launches the web server in on our IP but now with port 4104. With this, you would locally browse to http://127.0.0.1:4104. rather than http://127.0.0.1:8000

SimpleHTTPServer is quite handy when you’re in the middle of smaller web development projects and want to quickly check things in a browser or show it to someone; you don’t need to take the time move files about or commit it to a repository. SimpleHTTPServer runs on all Unix variants with python, including FreeBSD, Linux, Ubuntu, Redhat, and of course Mac OS X is included as well.

If you find any new or helpful uses for this great little trick give us a heads up.