Three Methods to Run Python Scripts as System Services

Dec 07, 2025 · Programming · 9 views · 7.8

Keywords: Python daemon | system service management | Linux background execution

Abstract: This article explores three main approaches for running Python scripts as background services in Linux systems: implementing custom daemon classes for process management, configuring services with Upstart, and utilizing Systemd for modern service administration. Using a cross-domain policy server as an example, it analyzes the implementation principles, configuration steps, and application scenarios of each method, providing complete code examples and best practice recommendations.

In Linux server environments, running Python scripts as background services is a common operational requirement. Ensuring script continuity and manageability after terminal sessions close is crucial for system design and deployment. This article uses a cross-domain policy server (Flash Policy Daemon) as an example to explore three methods for transforming Python scripts into system services.

Custom Daemon Class Implementation

By creating specialized daemon classes, Python scripts can be provided with standard service management interfaces. The core of this approach involves implementing a custom class that inherits from a base daemon class, encapsulating process start, stop, and restart logic. Below is a simplified implementation framework:

import sys
import time

from daemon import Daemon

class YourCode(object):
    def run(self):
        # Actual business logic
        while True:
            time.sleep(1)

class MyDaemon(Daemon):
    def run(self):
        your_code = YourCode()
        your_code.run()

if __name__ == "__main__":
    daemon = MyDaemon('/tmp/daemon-example.pid')
    if len(sys.argv) == 2:
        if 'start' == sys.argv[1]:
            daemon.start()
        elif 'stop' == sys.argv[1]:
            daemon.stop()
        elif 'restart' == sys.argv[1]:
            daemon.restart()
        else:
            print "Unknown command"
            sys.exit(2)
        sys.exit(0)
    else:
        print "usage: %s start|stop|restart" % sys.argv[0]
        sys.exit(2)

This method's advantage lies in providing a unified command-line interface, allowing developers to manage services through commands like python myscript.py start, python myscript.py stop, and python myscript.py restart. Additionally, PID file management ensures process state traceability.

Upstart Service Configuration

For Linux distributions using Upstart as the initialization system (e.g., CentOS 6), Python scripts can be registered as system services via configuration files. Upstart configuration files are typically located in the /etc/init/ directory. Below is a typical configuration example:

start on started sshd
stop on runlevel [!2345]

exec /usr/bin/python /opt/my_service.py
respawn

In this configuration, start on started sshd specifies the trigger condition for service startup, automatically launching the Python service after SSH service initiation. The respawn directive ensures automatic restart upon unexpected termination. After configuration, administrators can use start my-service, stop my-service, and restart my-service commands for service management.

Systemd Service Management

Modern Linux distributions (e.g., CentOS 7) widely adopt Systemd as the initialization system. Systemd offers more powerful and flexible service management capabilities. Below is a Systemd service unit file example for Python scripts:

[Unit]
Description=My Python daemon

[Service]
Type=simple
ExecStart=/usr/bin/python3 /opt/project/main.py
WorkingDirectory=/opt/project/
Environment=API_KEY=123456789
Environment=API_PASS=password
Restart=always
RestartSec=2

[Install]
WantedBy=sysinit.target

This configuration defines basic service properties: Type=simple indicates a simple background process; ExecStart specifies the startup command; WorkingDirectory sets the working directory; Environment defines environment variables; Restart=always ensures automatic restart upon abnormal termination. The configuration file should be saved as /etc/systemd/system/my_daemon.service, then enabled via:

systemctl daemon-reload
systemctl enable my_daemon
systemctl start my_daemon --no-block

Service status can be checked with systemctl status my_daemon, while log information is accessible via journalctl -u my_daemon.

Implementation Principle Analysis

The core of transforming Python scripts into system services lies in daemonization, typically involving these key steps:

  1. Process Separation: Create a child process via the fork() system call, then terminate the parent process, making the child an orphan process adopted by init.
  2. Session Leadership Acquisition: Call setsid() to create a new session and become session leader, detaching from terminal control.
  3. File Descriptor Handling: Close or redirect standard input, output, and error streams to prevent terminal association.
  4. Working Directory Change: Change the current working directory to root to avoid occupying unmountable file systems.
  5. Signal Handling: Set appropriate signal handlers for graceful termination requests.

In practical applications, cross-domain policy server implementation must consider specific networking requirements. The original Polserv class creates a TCP server listening on port 843, handling Flash policy file requests. Upon receiving specific request formats, the server returns XML policy files permitting cross-domain access.

Best Practice Recommendations

When selecting a service implementation approach, consider these factors:

  1. System Compatibility: Choose methods based on the target system's initialization system. Systemd is preferred for modern Linux distributions, while Upstart suits older systems.
  2. Management Complexity: Custom daemon classes offer maximum flexibility but require complete management logic implementation; Systemd and Upstart provide ready-made service management frameworks.
  3. Monitoring and Logging: Systemd integrates powerful logging systems (journald), facilitating service monitoring and troubleshooting.
  4. Resource Management: Systemd supports CPU, memory resource limits and isolation, suitable for production deployments.
  5. Security: Consider running services under non-privileged user accounts with appropriate file permissions and environment variables.

For the example cross-domain policy server, Systemd service management is recommended due to its comprehensive process monitoring, automatic restart, and log collection capabilities. Additionally, consider transforming the original single-threaded server to use asynchronous I/O or multi-process models for improved concurrency handling.

The article also discusses the fundamental differences between HTML tags like <br> and character sequences like \n, where the former are HTML markup elements for line breaks, while the latter are newline escape sequences in programming languages. In code examples, expressions like print("<T>") require angle bracket escaping to prevent misinterpretation as HTML tags.

Copyright Notice: All rights in this article are reserved by the operators of DevGex. Reasonable sharing and citation are welcome; any reproduction, excerpting, or re-publication without prior permission is prohibited.