Python - Flask - open a webpage in default browser

后端 未结 1 1547
梦谈多话
梦谈多话 2021-01-31 12:07

I am working on a small project in Python. It is divided into two parts.

First part is responsible to crawl the web and extract some infromation and insert them into a d

1条回答
  •  轻奢々
    轻奢々 (楼主)
    2021-01-31 12:46

    I use similar code on Mac OS X (with Safari, Firefox, and Chrome browsers) all the time, and it runs fine. Guessing you may be running into Flask's auto-reload feature. Set debug=False and it will not try to auto-reload.

    Other suggestions, based on my experience:

    • Consider randomizing the port you use, as quick edit-run-test loops sometimes find the OS thinking port 5000 is still in use. (Or, if you run the code several times simultaneously, say by accident, the port truly is still in use.)
    • Give the app a short while to spin up before you start the browser request. I do that through invoking threading.Timer.

    Here's my code:

    import random, threading, webbrowser
    
    port = 5000 + random.randint(0, 999)
    url = "http://127.0.0.1:{0}".format(port)
    
    threading.Timer(1.25, lambda: webbrowser.open(url) ).start()
    
    app.run(port=port, debug=False)
    

    (This is all under the if __name__ == '__main__':, or in a separate "start app" function if you like.)

    0 讨论(0)
提交回复
热议问题