Set the current directory when running a SimpleHTTPServer

Solution 1:

If you're using SimpleHTTPServer directly from command line, you can simply use shell features:

pushd /path/you/want/to/serve; python -m SimpleHTTPServer; popd

In Python 3 you have to use:

pushd /path/you/want/to/serve; python -m http.server; popd

The SimpleHTTPServer module has been merged into http.server in Python 3.0

Solution 2:

Doing it without changing directory on Linux:

bash -c "cd /your/path; python -m SimpleHTTPServer"

Solution 3:

You can create a script for this (say microserver.sh), and put this inside

#!/bin/bash

pushd /your/directory/
python -m SimpleHTTPServer 8000 &> /dev/null &
popd

Then, change the permissions:

chmod +x microserver.sh

And execute it:

./microserver.sh

This will avoid printing messages to the console and send the process to the background, so you can continue using the console for other things.

Also, it could be called from other scripts, e.g. it can be added to the ~/.bashrc to start the server upon starting the user session. Just add this at the end of the .bashrc

. ./microserver.sh