Dmitry Pleshkov
Dmitry Pleshkov

Reputation: 1257

Flask: Find first open port

How can I find the first open HTTP port on my computer, and start a Flask server running on it?

I will run the app like this:

app.run(port=first_open_port, host='0.0.0.0')

Upvotes: 1

Views: 1388

Answers (1)

Finlay McWalter
Finlay McWalter

Reputation: 1342

It probably feels like a hack, but at least in development (which is the only time they recommend you use app.run anyway) you can simply start with a port number, wrap the app.run in a try:except: block, and if it throws a socket.error you increment your candidate port# and retry.

for port in range(100, 5000):
    try:
        app.run(port=port)
        break
    except socket.error:
        pass

Upvotes: 6

Related Questions