Five Ways to Run Python Scripts in the Background on Linux
This article provides a comprehensive guide to five methods for running Python scripts in the background on Linux, covering nohup with &, screen sessions, systemd services, Celery task queues, and supervisord, including command examples and configuration steps.
1. Use nohup command
The nohup command runs a program on a remote server and redirects output to nohup.out . Execute a Python script in the background with:
<code>nohup python script.py &</code>The trailing & puts the process in the background and returns a PID; output can be inspected in nohup.out .
2. Use screen command
screen creates detachable terminal sessions that persist after SSH disconnects. Start a session and run the script:
<code>screen -S mysession
python script.py</code>Detach with Ctrl+A D to return to the console while the script continues.
3. Use systemd service
Systemd manages services on Linux. Create a unit file /etc/systemd/system/myscript.service :
<code>[Unit]
Description=My Python Script
After=multi-user.target
[Service]
Type=idle
ExecStart=/usr/bin/python3 /path/to/script.py
[Install]
WantedBy=multi-user.target</code>Reload the daemon, start the service, and check its status:
<code>sudo systemctl daemon-reload
sudo systemctl start myscript
sudo systemctl status myscript</code>4. Use Celery task queue
Celery enables asynchronous task execution. Install it, define a task, start a worker, and call the task:
<code>pip install celery</code> <code>from celery import Celery
app = Celery('task', backend='rpc://', broker='amqp://localhost')
@app.task
def mytask():
# task logic
</code> <code>celery -A tasks worker</code> <code>from tasks import mytask
mytask.delay()</code>5. Use supervisord
Supervisord controls processes. Install it, create a config file /etc/supervisor/conf.d/myscript.conf :
<code>[program:myscript]
command=/usr/bin/python /path/to/script.py
autostart=true
autorestart=true
stderr_logfile=/var/log/myscript.err.log
stdout_logfile=/var/log/myscript.out.log
user=username</code>Reload the configuration and start the script:
<code>sudo supervisorctl reread
sudo supervisorctl update
sudo supervisorctl start myscript</code>These five approaches—nohup, screen, systemd, Celery, and supervisord—provide flexible options for running Python programs as background services on Linux systems.
Python Programming Learning Circle
A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.