Skip to main content

Steps to Create a systemd Service for Your Python Script (+venv)

  1. Create a systemd Service Unit File: Create a service unit file for your Python script. This file defines how the service is run and managed. Place the file in /etc/systemd/system/ with a .service extension, for example, myscript.service.
  2. Define the Service Unit File: Add the following content to the service unit file. Adjust the paths and parameters according to your setup:
    • Description: A short description of the service.
    • After: Specifies the order in which services should be started (optional).
    • User: The user under which the script will run.
    • WorkingDirectory: The directory where the script is located.
    • ExecStart: The command to start your Python script, using the Python interpreter from your virtual environment.
    • Restart: Specifies the restart policy (e.g., restart on failure).
  3. Reload systemd to Apply the Changes: After creating or modifying the service unit file, reload systemd to recognize the new or updated service.
  4. Start the Service: Start the service using systemctl:
  5. Enable the Service to Start on Boot: To ensure that the service starts automatically on boot, enable it:
  6. Check the Status of the Service: To check the status of the service and see if it’s running correctly:
  7. View Logs for Debugging: To view logs for the service, which can be useful for debugging:
By following these steps, you can effectively manage your Python script as a service using systemd.