Start Simple HttpServer in a thread and open the browser
suggest changeUseful if your program is outputting web pages along the way.
from http.server import HTTPServer, CGIHTTPRequestHandler
import os
import webbrowser
import threading
def start_server(path, port=8000):
'''Start a simple webserver serving path on port'''
os.chdir(path)
httpd = HTTPServer(('', port), CGIHTTPRequestHandler)
httpd.serve_forever()
# Start the server in a new thread
port = 8000
daemon = threading.Thread(name='daemon_server',
target=start_server,
args=('.', port),
daemon=True) # Killed once the main thread is dead.
daemon.start()
# Open the web browser
webbrowser.open('http://localhost:{}'.format(port))
Thread.setDaemon is deprecated. Pass daemon=True. CGIHTTPRequestHandler serves files and can run CGI scripts in that directory. This script ends after webbrowser.open, so the daemon server is shut down immediately unless the main thread keeps running.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents