Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Start http web server then open browser

I'm trying to start a simple HTTP server then open it in the default browser. I don't know what I'm doing wrong, it's either not starting the server at all, or it's stopping as soon as it gets to the end of the script (isn't it supposed to run forever?).

import BaseHTTPServer, SimpleHTTPServer, webbrowser, thread
def start_server():
  httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 3600), SimpleHTTPServer.SimpleHTTPRequestHandler)
  httpd.serve_forever()
thread.start_new_thread(start_server,())
url = 'http://127.0.0.1:3600'
webbrowser.open_new(url)
like image 985
fadelm0 Avatar asked Jun 14 '26 08:06

fadelm0


2 Answers

A thread continues to exist as long as the application continues to run, in the case webbrowser.open_new() is not blocking so the browser will hardly finish running the application, what you should do is make a blocker to prevent the application finish of execute:

import sys
import thread
import webbrowser
import time

import BaseHTTPServer, SimpleHTTPServer

def start_server():
    httpd = BaseHTTPServer.HTTPServer(('127.0.0.1', 3600), SimpleHTTPServer.SimpleHTTPRequestHandler)
    httpd.serve_forever()

thread.start_new_thread(start_server,())
url = 'http://127.0.0.1:3600'
webbrowser.open_new(url)

while True:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        sys.exit(0)
like image 81
eyllanesc Avatar answered Jun 15 '26 22:06

eyllanesc


Here is a Python 3 version of the answer by @eyllanesc using the newer http.server and the threading module

import sys
import time
import threading
import webbrowser
from http.server import HTTPServer, SimpleHTTPRequestHandler

ip = "127.0.0.1"
port = 3600
url = f"http://{ip}:{port}"


def start_server():
    server_address = (ip, port)
    httpd = HTTPServer(server_address, SimpleHTTPRequestHandler)
    httpd.serve_forever()


threading.Thread(target=start_server).start()
webbrowser.open_new(url)

while True:
    try:
        time.sleep(1)
    except KeyboardInterrupt:
        sys.exit(0)
like image 28
Dylan Hogg Avatar answered Jun 15 '26 21:06

Dylan Hogg