Issue
I am implementing a GUI in Python/Flask. The way flask is designed, the local host along with the port number has to be "manually" opened.
Is there a way to automate it so that upon running the code, browser(local host) is automatically opened?
I tried using webbrowser package but it opens the webpage after the session is killed.
I also looked at the following posts but they are going over my head.
Shell script opening flask powered webpage opens two windows
Problem occurs when html pages are rendered based on user inputs.
Thanks in advance.
import webbrowser
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
if __name__ == "__main__":
webbrowser.open_new('http://127.0.0.1:2000/')
app.run(port=2000)
Solution
Use timer to start new thread to open web browser.
import webbrowser
from threading import Timer
from flask import Flask
app = Flask(__name__)
@app.route("/")
def hello():
return "Hello World!"
def open_browser():
webbrowser.open_new("http://127.0.0.1:5000")
if __name__ == "__main__":
Timer(1, open_browser).start()
app.run(port=2000)
Answered By - Sunil Goyal
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.