在CherryPy中启动浏览器

2 投票
1 回答
556 浏览
提问于 2025-04-15 23:35

我有一个用来显示的html页面...

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

当页面加载完成后(比如通过命令 'python mypage.py' 启动),我想要自动打开浏览器来显示这个页面(比如通过 http://localhost/8000)。有没有什么方法可以实现这个(比如在CherryPy中使用某种钩子),还是说我必须手动打开浏览器(比如双击一个图标)?

谢谢大家!
艾伦

1 个回答

4

你可以把你的网页浏览器连接到引擎的启动和停止过程:

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

或者,你可以解压快速入门包:

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()

撰写回答