Predictive Hacks

How To Manage Multiple Screen Sessions

Photo by NordWood Themes on Unsplash

Linux’s Screen lets you run terminal applications to a Server in the background even if you disconnect from the ssh connection. It’s especially useful for us when running APIs or Web Apps like Streamlit.

The problem with Screen is that if the server goes down for any reason like update, restart, etc. you have to run all the screen sessions manually one by one. A great solution for it is to create an executable file and add all the screen sessions there.

The Executable

Firstly we need to create a “sh” file having in its first line the following.

#!/bin/sh

Then, we need to add the screen session commands.

The screen command has to do the following:

  1. Start a Screen Session
  2. Activate the App/API Environment(if any)
  3. Navigate to App/API’s path
  4. Run the App/API
  5. Detach the Screen Session

To achieve all these 5 steps, we can run the following:

screen -dmS app_name bash -c 'cd /path_to_app; conda activate app_env; /path_to_app/app.py'

Let’s break down this line of code.

–dmS: Opens a Screen Session and then detaches it.
bash -c: Runs a bash script. We separate every bash command with a ‘;’.
In the script, we first navigate to the app/api’s directory, and then using the app/api’s environment, we run the file.

Tip: In order to find the full path of the Python or Streamlit of the app/api’s environment, you can run the following when it’s activated:

for Python:

which python

for Streamlit:

which streamlit

Putting It All Together

Now, Let’s add some screen session examples in our .sh file. Let’s call it screens.sh.

#!/bin/sh

screen -dmS python_api bash -c 'cd /python_api; /home/conda/envs/custom_env/bin/python /python_api/app.py'

screen -dmS streamlit_app bash -c 'cd /streamlit_app; ~/.conda/envs/custom_env/bin/streamlit run /streamlit_app/app.py'


Finally, you can run the screens.sh, running the following:

./screens.sh

Now you should have all your screen sessions running and detached.

As a bonus, you can kill all the screen sessions at once using the following command:

pkill screen

Share This Post

Share on facebook
Share on linkedin
Share on twitter
Share on email

Leave a Comment

Subscribe To Our Newsletter

Get updates and learn from the best

More To Explore

Python

Image Captioning with HuggingFace

Image captioning with AI is a fascinating application of artificial intelligence (AI) that involves generating textual descriptions for images automatically.