adlfkjfadslkjfads

Python Tip of the Day - Simple HTTP Server

Posted on Tue 17 April 2018 in Posts

This is kind of an old tip, but back in the days of Python 2 (aka Legacy Python) a quick tip for sharing a folder of files was to use the built in SimpleHTTPServer module to quickly host a bunch of files:

python -m SimpleHTTPServer

which spins up a basic http server on port 8000 that by default shows all the files in the directory from where it is run. This is a very quick and handy way for sharing files with a coworker as (so long as they know and can reach your IP address), you just fire up this server, then they can grab files, then you turf the server.

Python 3 unfortunately (or fortunately, I dunno) renamed the module, leading to moments of confusion (ie "why doesn't that command not work anymore now that I'm in a virtual environment with Python 3?"). The equivalent in Python3 is:

python -m http.server

But y'know what, I don't want to have to think about which version of Python I'm running, I just want a simple command to fire up the server and have it figure out which module to run. Hence this StackOverflow answer, which indicates you can add this to your .bashrc file (or equivalent for your shell):

alias serve="python -m $(python -c 'import sys; print("http.server" if sys.version_info[:2] > (2,7) else "SimpleHTTPServer")')"

Now from any directory a simple serve will start up the appropriate simple http server.