Open browser automatically when Python code is executed

Question:

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)
Asked By: Abhishek Kulkarni

||

Answers:

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

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

Answered By: Yaakov Bressler

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

Answered By: Kimbly Labs