14

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

python webbrowser.open(url)

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)

3 Answers 3

38

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)
Sign up to request clarification or add additional context in comments.

Comments

2

I'd suggest the following improvement to allow for loading of the browser when in debug mode:
Inspired by this answer, will only load the browser on the first run...

def main():
    
    # The reloader has not yet run - open the browser
    if not os.environ.get("WERKZEUG_RUN_MAIN"):
        webbrowser.open_new('http://127.0.0.1:2000/')

    # Otherwise, continue as normal
    app.run(host="127.0.0.1", port=2000)

if __name__ == '__main__':
    main()

https://stackoverflow.com/a/9476701/10521959

Comments

-1

It opens two tabs of the browser. Also you are running the application on port 2000 while opening browser at port 5000.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.