Set the current directory when running a SimpleHTTPServer


Is there any way to set the directory where you want to start a SimpleHTTPServer or BaseHTTPServer?

Asked By: Eldelshell



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

Answered By: nkrkv

Doing it without changing directory on Linux:

bash -c "cd /your/path; python -m SimpleHTTPServer"
Answered By: Naveen

You can create a script for this (say, and put this inside


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

Then, change the permissions:

chmod +x

And execute it:


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

. ./

Answered By: toto_tico

If instead of command line you need to run it from your code, SimpleHTTPRequestHandler receive a directory argument that its default value is current directory:

def __init__(self, *args, directory=None, **kwargs):
    if directory is None:
        directory = os.getcwd()

You can use it like this:

import http.server

class Handler(http.server.SimpleHTTPRequestHandler):

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs, directory='/path/to/your/dir')

def main():
    http.server.test(Handler)  # test(Handler, port=8080)

if __name__ == '__main__':
Answered By: iman
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.