Running a Python script in Terminal without losing it by a connection drop

Sometimes you will need to run a small code in Python via terminal. Let’s guarantee it’s keep running even if the connection drops.

Table of contents

No heading

No headings in the article.

To run a Python script in the background without losing its execution if the connection to the server drops, you can use a tool called nohup to run the script. nohup stands for "no hangup," and it allows you to run a command in the background even if you close the terminal or log out of the system.

Here's the general syntax for running a Python script in the background with nohup:

nohup python script.py &

This will run the script in the background, and the output will be saved to a file called nohup.out.

If you want to run the script in the background and redirect the output to a specific file, you can use the following syntax:

nohup python script.py > output.log 2>&1 &

This will run the script in the background and redirect both the standard output and standard error to the file output.log.

You can also use the screen command to run the script in the background. The screen command allows you to create a new terminal session and run the script within that session. You can then detach the session and log out, and the script will continue running in the background.

Here's the general syntax for running a Python script in the background with screen:

screen -S session_name
python script.py
Ctrl-A D

This will create a new screen session called session_name, run the script within that session, and then detach the session. The script will continue running in the background.

To reattach to the session later, use the following command:

screen -r session_name

This will allow you to view the output of the script and any errors that may have occurred.

I hope it helps if you are getting into a similar situation :)