this is my Python3 project hiearchy:
projet
\
script.py
web
\
index.html
From script.py
, I would like to run a http server which serve the content of the web
folder.
Here is suggested this code to run a simple http server:
import http.server
import socketserver
PORT = 8000
Handler = http.server.SimpleHTTPRequestHandler
httpd = socketserver.TCPServer(("", PORT), Handler)
print("serving at port", PORT)
httpd.serve_forever()
but this actually serve project
, not web
. How can I specify the path of the folder I want to serve?
Just for completeness, here's how you can setup the actual server classes to serve files from an arbitrary directory:
Then you can set any arbitrary path in your code:
If you just want serve static file you can do it by running SimpleHTTPServer module using python 2:
Or with python 3:
This way you do not need to write any script.
https://docs.python.org/3/library/http.server.html#http.server.SimpleHTTPRequestHandler
So you just need to change the current directory prior to starting the server - see
os.chdir
eg:
In Python 3.7
SimpleHTTPRequestHandler
can take adirectory
argument:and from the command line:
To get a little crazy... you could make handlers for arbitrary directories: