Search code examples
pythonbrowsercherrypy

Launching browser within CherryPy


I have a html page displayed using...

cherrypy.quickstart(ShowHTML(htmlfile), config=configfile)

Once the page is loaded (eg. initiated via. the command 'python mypage.py'), I would like to automatically launch the browser to display the page (eg. via. http://localhost/8000). Is there any way I can achieve this (eg. via. a hook within CherryPy), or do I have to call-up the browser manually (eg. by double-clicking an icon)?

TIA Alan


Solution

  • You can either hook your webbrowser into the engine start/stop lifecycle:

    def browse():
        webbrowser.open("http://127.0.0.1:8080")
    cherrypy.engine.subscribe('start', browse, priority=90)
    

    Or, unpack quickstart:

    from cherrypy import config, engine, tree
    
    config.update(configfile)
    tree.mount(ShowHTML(htmlfile), '/', configfile)
    if hasattr(engine, "signal_handler"):
        engine.signal_handler.subscribe()
    if hasattr(engine, "console_control_handler"):
        engine.console_control_handler.subscribe()
    
    engine.start()
    webbrowser.open("http://127.0.0.1:8080")    
    engine.block()