Make http.server automatically open a page

With the http.server module, one can start an http server, that serves static files from the current or another given directory.

Often, the workflow is to start a web server on the command line (python -m http.server) and after that open the address in a web browser. This is hard to automate in a script, because before you start the server you can’t be sure it succeeds to start. And when the server has been started, you need to work with multiple processes to open the page in a web browser. So usually one needs to open the web page manually after starting the web-server.

I would like to add arguments to the http.server module to open the server in a browser via the module webbrowser. I think of the following arguments:

[-n | --window | -t | --tab] [path]

When adding the --window argument, after the http server has been succesfully started, the url to the server is opened in a new browser window via webbrowser. Same goes for --tab, only this time it will be opened in a new tab.

When path has been specified, the server-url that will be opened will have this path be appended.

One issue though: port is now a positional argument, which might cause problems with my proposed path. This could be solved by making adding a optional --port argument and removing the positional port argument. To keep backwards compatibility, the path could be interpreted as port when it’s all digits and no --port argument has been supplied. To open a path that contains digits only, one must specify the --port argument`.

The -n and -t arguments are for compatibility with the webbrowser module.

Not sure if prior art is important, but I got the idea from jekyll’s --open-url argument, which is really handy.

What do you guys think?

4 Likes

There is a precedent in the standard library: pydoc -b starts a webserver and opens a browser
https://docs.python.org/3/library/pydoc.html

I would suggest to replicate this for http.server: add one option -b and let the browser settings decide if a new window or tab should be opened.

1 Like