How To Run A Python Script As A Service On CentOS?

Published August 9, 2024

Problem: Running Python Scripts as Services on CentOS

Running Python scripts as services on CentOS can be difficult. This setup lets scripts start automatically when the system boots and run in the background. However, it needs specific configuration steps. You must create a service file and set up the system to manage the script as a service.

Methods to Run Python Scripts as Services

Using Systemd

Systemd manages services for Linux operating systems. It controls what programs run when a Linux system starts. To use Systemd for running Python scripts as services:

  1. Create a service file in /etc/systemd/system/.
  2. Define service parameters, including the Python script path.
  3. Set service file permissions.
  4. Reload the Systemd daemon.
  5. Enable and start the service.

Example: Creating a Systemd Service File

Create a file named myscript.service in /etc/systemd/system/ with the following content:

[Unit]
Description=My Python Script Service
After=network.target

[Service]
ExecStart=/usr/bin/python3 /path/to/your/script.py
Restart=always
User=yourusername

[Install]
WantedBy=multi-user.target

Replace /path/to/your/script.py with the actual path to your Python script and yourusername with the user you want the script to run as.

Using Supervisor

Supervisor is a system that helps you monitor and control processes on UNIX-like operating systems. It's useful for managing long-running Python scripts. To use Supervisor:

  1. Install Supervisor with the package manager.
  2. Create a configuration file for your Python script in Supervisor's configuration directory.
  3. Define program parameters, including the command to run your script.
  4. Update Supervisor to recognize the new configuration.
  5. Start the program using Supervisor's control commands.

Tip: Automatic Restart with Supervisor

To make sure your Python script restarts automatically if it crashes, add the following line to your Supervisor configuration file:

autorestart=true

This ensures that Supervisor will restart your script if it exits unexpectedly, maintaining continuous operation.

Both methods offer reliable ways to run Python scripts as services. Systemd integrates well with modern Linux systems, while Supervisor provides specific process management features.

Creating a Systemd Service for Your Python Script

Writing the Service File

To create a Systemd service for your Python script, you need to write a service file. This file defines how the service runs and behaves. The service file has a structure with different sections:

  1. [Unit]: Contains metadata and dependencies.
  2. [Service]: Defines the service behavior and execution.
  3. [Install]: Specifies how to install the service.

When configuring the service file, focus on two key parameters:

  • ExecStart: This specifies the command to start your Python script. Use the full path to both the Python interpreter and your script.
  • WorkingDirectory: This sets the working directory for your script. It's important if your script uses relative file paths.

Example service file structure:

[Unit]
Description=My Python Script Service
After=network.target

[Service]
ExecStart=/usr/bin/python3 /path/to/your/script.py
WorkingDirectory=/path/to/script/directory
Restart=always
User=yourusername

[Install]
WantedBy=multi-user.target

Replace the placeholders with your specific paths and username.

Tip: Use Environment Variables

You can set environment variables for your Python script in the service file. Add a line like this in the [Service] section:

Environment=PYTHONPATH=/path/to/your/python/modules

This is useful for setting configuration options or paths that your script needs.

Enabling and Starting the Service

After creating the service file, you need to enable and start it. Use these commands:

  1. Reload the Systemd daemon to recognize the new service file:

    sudo systemctl daemon-reload
  2. Enable the service to start on boot:

    sudo systemctl enable your_service_name.service
  3. Start the service:

    sudo systemctl start your_service_name.service
  4. Check the service status:

    sudo systemctl status your_service_name.service

This status command will show if the service is running or if there are any issues. If you see "Active: active (running)", your Python script is now running as a service.

Setting Up Supervisor for Your Python Script

Installing Supervisor

To install Supervisor on CentOS:

  1. Update your system packages:

    sudo yum update
  2. Install EPEL repository if not installed:

    sudo yum install epel-release
  3. Install Supervisor:

    sudo yum install supervisor
  4. Start the Supervisor service:

    sudo systemctl start supervisord
  5. Enable Supervisor to start on boot:

    sudo systemctl enable supervisord

To check the installation, view the Supervisor status:

sudo systemctl status supervisord

This command should show that Supervisor is active and running.

Tip: Verify Supervisor Version

After installing Supervisor, you can check its version to make sure you have the latest one:

supervisord --version

This command will display the current version of Supervisor installed on your system.

Configuring Supervisor

To configure Supervisor for your Python script:

  1. Create a new configuration file in the Supervisor configuration directory:

    sudo nano /etc/supervisord.d/your_script_name.ini
  2. Add this content to the file:

    [program:your_script_name]
    command=/usr/bin/python3 /path/to/your/script.py
    directory=/path/to/script/directory
    user=your_username
    autostart=true
    autorestart=true
    stderr_logfile=/var/log/your_script_name.err.log
    stdout_logfile=/var/log/your_script_name.out.log

    Replace the placeholders with your paths and username.

  3. Save the file and exit the editor.

  4. Reload Supervisor to apply the new configuration:

    sudo supervisorctl reread
    sudo supervisorctl update
  5. Start your program:

    sudo supervisorctl start your_script_name

These steps will set up Supervisor to manage your Python script as a service, keeping it running and restarting it if it stops.

Managing Your Python Service

Monitoring Service Status

To check your Python service health, use these commands:

For Systemd:

sudo systemctl status your_service_name

For Supervisor:

sudo supervisorctl status your_program_name

These commands show if your service is running, stopped, or has issues.

To view logs and fix problems:

For Systemd:

sudo journalctl -u your_service_name

For Supervisor:

sudo tail -f /var/log/your_program_name.out.log
sudo tail -f /var/log/your_program_name.err.log

These commands show the latest log entries, helping you find and fix issues.

Tip: Filter Systemd Logs

To filter Systemd logs for a specific time range, use the --since and --until options:

sudo journalctl -u your_service_name --since "2023-05-01" --until "2023-05-02"

This command shows logs from May 1st to May 2nd, 2023.

Stopping and Restarting Services

To control your Python service, use these commands:

For Systemd:

  • Stop: sudo systemctl stop your_service_name
  • Start: sudo systemctl start your_service_name
  • Restart: sudo systemctl restart your_service_name

For Supervisor:

  • Stop: sudo supervisorctl stop your_program_name
  • Start: sudo supervisorctl start your_program_name
  • Restart: sudo supervisorctl restart your_program_name

To automate restarts:

For Systemd, add this line to your service file:

Restart=always

For Supervisor, add this line to your program configuration:

autorestart=true

These settings make your service restart automatically if it stops unexpectedly.