If you need to fire up a web server to serve some files but installing apache or nginx is overkill using a simple script to serve your files is arguably one of the best ways to do it. In this post I have a simple python script that will serve a directory of files on your system via HTTP. I typically use this script to run reveal.js presentations that I create in markdown because in order to do that you need a web server but for a simple presentation I cant justify installing a full blown web server on my workstation.

If you would like to just grab the code you can find it out on my Github at https://github.com/superadm1n/BasicHTTPServer otherwise in this post I will show you how to use the server from the command line.

Running the Server

The simplest way to run the script to serve your files is to just run the file directly

python server.py

This will serve the directory that the server.py file is located in and the server will listen on address 127.0.0.1 and port 8000.

You can also specify what directory you want to serve, the port, and address the server listens on via command line arguments. Below is the output using the '-h' argument which will show you all of the available command line arguments.

$ python server.py -h
usage: server.py [-h] [--port PORT] [--ipaddr IPADDR] [--webdir WEBDIR]

optional arguments:
  -h, --help       show this help message and exit
  --port PORT      Port to serve on (Default: 8000)
  --ipaddr IPADDR  IP Address to serve on (Default: 127.0.0.1)
  --webdir WEBDIR  Directory to serve (Default will serve the directory the
                   file is in)

$

It is pretty self explanatory how to use the arguments here so I wont go into detail as to the possible combinations of arguments you can have other than you can specify just one or all when running the server. Once you issue a valid command it will let you know it is serving files and you will be able to see any request that comes in.

$ python server.py 
Serving directory '/home/kyle/code/presentations' on port 8000 bound to address 127.0.0.1

I have designed it by default to only serve files on port 8000 to the loopback address in the event that you don't know what you are doing and start serving a directory that you shouldn't like "C:\" or "/" in Linux you don't serve all of your files to the network!

Stopping the Server

Once you are done and no longer need to run the server you can simply hit control+c and the server will close and you can continue with your day.

 

I hope this is able to help you quickly serve files on a system that has python installed on it.