2

I am trying to create a program that will start a server with the Bottle module and then open the server url with the webbrowser module. I am having issues opening the webbrowser AFTER starting the bottle server. If i open webbrowser before starting the bottle server the webbrowser successfully opens. However, the webbrowser never opens if I start the bottle server before opening the webbrowser.

import webbrowser
from bottle import route, run, request


def step1():
    url = 'http://localhost:8080'
    chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s --incognito'
    webbrowser.get(chrome_path).open_new(url)

run(host='', port=8080)

step1()

I expect the server to start and then for the webbrowser to open. However, the webbrowser just doesn't open and no errors are thrown.

In this example, opening the webbrowser before running the server works and the connection is successful. However, if I wanted to make a more complex webbrowser function that requires feedback from the server it wouldn't work.

Is there a way to open a webbrowser AFTER starting a bottle server?

Thanks!

2 Answers2

0

Rus this script in console, open you Chrome and point it to http://localhost:8181/hello/Russell

import webbrowser
from bottle import route, run, template

@route('/hello/<name>')
def index(name):
    url = 'http://localhost:8181/hello/Russell'
    chrome_path = '"C:/Program Files (x86)/Google/Chrome/Application/chrome.exe" %s --incognito'
    webbrowser.get(chrome_path).open_new(url)
    return template('<b>Hello, <font color=red size=+2>{{name}}</font></b>!', name=name)

run(host='localhost', port=8181)
An0ther0ne
  • 324
  • 3
  • 8
0

Async is your friend here.

import gevent
from gevent import monkey, joinall, spawn, signal
monkey.patch_all()
from gevent.pywsgi import WSGIServer
import webbrowser
import bottle
from bottle import route, run, request, get

@get('/')
def home():
    return 'Hello World'

def step1():
    url = 'http://localhost:8080'
    chrome_path = 'C:/Program Files (x86)/Google/Chrome/Application/chrome.exe %s --incognito'
    webbrowser.get(chrome_path).open_new(url)

if __name__ == '__main__':
    print('Started...')
    botapp = bottle.app()
    server = WSGIServer(("0.0.0.0", int(8080)), botapp )

    def shutdown():
        print('Shutting down ...')
        server.stop(timeout=60)
        exit(signal.SIGTERM)
    gevent.signal(signal.SIGTERM, shutdown)
    gevent.signal(signal.SIGINT, shutdown) #CTRL C
    threads = []
    threads.append(spawn(server.serve_forever))
    threads.append(spawn(step1))
    joinall(threads)
eatmeimadanish
  • 3,809
  • 1
  • 14
  • 20