Running Python Scripts in the Background on Linux

Running in the Foreground

To run a Python script (for example, download.py) in Linux, execute it directly in the command line

python download.py

This runs in the foreground, and if the foreground is closed, the program will be interrupted, which is quite inconvenient.

Methods for Running in the Background

nohup python -u download.py > output.log 2>&1 &

nohup: This stands for no hang up, meaning it will run continuously without being interrupted;

python: Indicates the version of the Python interpreter to be used;

-u: Runs Python in unbuffered mode, meaning the output is flushed immediately rather than being cached and output together;

download.py: The name of the Python code file to be executed;

>: Redirects standard output;

output.log: Specifies the name of the log file;

2>&1: Redirects standard error output to the same location as standard output;

&: Causes the command to run in the background

View Running Information

cat output.log

Verify if the Script is Running in the Background

ps aux | grep download.py

Terminate the Running Process

pkill -f download.py

Leave a Comment