If you're calling it from shell, you can just use shell features and do:
For Python 2:
pushd /path/you/want/to/serve; python -m SimpleHTTPServer; popd
For Python 3.6 you don't even need to do that.
There's a directory argument to http.server
, so just do:
python3 -m http.server -d /path/you/want/to/serve
However, if you want to call it programatically, the solution proposed by Andy Hayden on "How to run a http server which serves a specific path?" seems more appropriate.
(It's less 'hacky'/ dependent on side effects, and uses the class constructor instead.)
Goes like this:
import http.server
import socketserver
PORT = 8000
DIRECTORY = "web"
class Handler(http.server.SimpleHTTPRequestHandler):
def __init__(self, *args, **kwargs):
super().__init__(*args, directory=DIRECTORY, **kwargs)
with socketserver.TCPServer(("", PORT), Handler) as httpd:
print("serving at port", PORT)
httpd.serve_forever()
The code above works for Python >= 3.6
For Python up to 3.5, there was no contextmanager protocol available for TCPServer's base class, but that just means you need to change the with
statement and turning it into a plain assignment:
httpd = socketserver.TCPServer(("", PORT), Handler)
Credits to Anthony Sottile for this last detail.