How to run two flask servers on different ports at the same time using bash script

Issue

I have two python files.

server1.py

from flask import Flask

app = Flask(__name__)

@app.route('/')
def home():
    return "Hello world from server 1."


if __name__ == "__main__":
    app.run(port=3000)

server2.py

from flask import Flask

app = Flask(__name__)


@app.route('/')
def home():
    return "Hello from server 2."


if __name__ == "__main__":
    app.run(port=4000)

Now, I need to run these two servers at the same time using a bash script.

I have tried this in my bash script.

python3 server1.py && python3 server2.py

When I run this bash script, it runs the server1.py file only when I quit server 1 it runs the server2.py

Output of my bash script:

* Serving Flask app 'server1' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:3000 (Press CTRL+C to quit)
^C * Serving Flask app 'server2' (lazy loading)
 * Environment: production
   WARNING: This is a development server. Do not use it in a production deployment.
   Use a production WSGI server instead.
 * Debug mode: off
 * Running on http://127.0.0.1:4000 (Press CTRL+C to quit)

I think its not possible to run two flask servers same time in a single terminal.
Is there any way using bash we can open a new terminal and run the server2.py file on that terminal? for some reasons, I need to run both flask servers same time.

Solution

Specifying && tells Bash to wait for the first command to successfully exit before running the second one.
A better solution might be first_command & second_command &.
This will send both scripts to run in the background at the same time and free up your TTY.
I wrote a post about Linux command chaining a few years ago, you might find it beneficial given your requirement.
You can read it here

Answered By – Orel Fichman

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published