Running a Python script continuously in the background on an Ubuntu system can be highly beneficial for various tasks like monitoring, data processing, or automation. In this blog post, we'll guide you through the process of creating an always-running Python script using systemd, a powerful service manager in Ubuntu. By following the steps below, you'll ensure that your Python script remains active even after system restarts and user logouts.
Prerequisites:
- Basic familiarity with Python programming.
- An Ubuntu system (tested on Ubuntu 18.04 and above).
- A Python script you want to run continuously.
Step 1: Creating the Python Script:
#!/usr/bin/env python3
import time
while True:
# Your script's main functionality goes here
print("Running my_script.py...")
time.sleep(10) # Adjust this value as needed for the interval between iterations
Step 2: Making the Python Script Executable:
chmod +x my_script.py
Step 3: Creating a systemd Service Unit File:
[Unit]
Description=My Python Script
After=network.target
[Service]
Type=simple
WorkingDirectory=/path/to/your/script/directory
ExecStart=/path/to/your/script/directory/my_script.py
Restart=always
RestartSec=10
[Install]
WantedBy=multi-user.target
Replace /path/to/your/script/directory with the actual path to the directory where my_script.py is located.
Step 4: Starting and Enabling the Service:
sudo systemctl start my_script
sudo systemctl enable my_script
Step 5: Checking the Status of the Service:
sudo systemctl status my_script
The output should indicate that the service is active and running.
By following the above steps, you've successfully created an always-running Python script on your Ubuntu system. The script will continue to run in the background, even after you log out or restart your system. With this approach, you can build powerful and persistent automation tasks, data processing, or monitoring applications with ease.
Remember to regularly check the status of your service and review logs for any potential issues. With your Python script continuously running, you can now focus on other tasks while enjoying the benefits of automation and background processing. Happy coding!

0 Comments