Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python SimpleHTTPServer serve a subdirectory

Is it possible to serve a subdirectory instead of the current directory with SimpleHTTPServer ?

I use it from the command-line like so:

python -m SimpleHTTPServer 5002

The reason I would like to use this is that I have a target folder which I delete from time to time and is regenerated by my tooling. However when I do that I need to restart the SimpleHTTPServer as well. I think that serving it from the parent repository would allow me not to restart it.

like image 412
nha Avatar asked Oct 15 '25 15:10

nha


1 Answers

Well, to serve the parent directory, just change the current working directory before running your Python script (python -m SimpleHTTPServer 5002).

You can write your own script, eg.: 'my_server.py':

import SimpleHTTPServer
import os


def main():
    pwd = os.getcwd()
    try:
        os.chdir("..")  # or any path you like
        SimpleHTTPServer.test()
    finally:
        os.chdir(pwd)


if __name__ == "__main__":
    main()

Then run 'my_server.py':

python -m my_server 5002
like image 154
Laurent LAPORTE Avatar answered Oct 18 '25 08:10

Laurent LAPORTE



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!