Steps to Create a systemd Service for Your Python Script (+venv)
-
Create a
systemdService 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.serviceextension, for example,myscript.service.sudo nano /etc/systemd/system/myscript.service -
Define the Service Unit File:
Add the following content to the service unit file. Adjust the paths and parameters according to your setup:
[Unit] Description=My Python Script Service After=network.target [Service] Type=simple User=root WorkingDirectory=/path/to/your/script ExecStart=/path/to/venv/bin/python /path/to/your/script/main.py Restart=on-failure [Install] WantedBy=multi-user.targetDescription: 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).
-
Reload
systemdto Apply the Changes:After creating or modifying the service unit file, reload
systemdto recognize the new or updated service.sudo systemctl daemon-reload -
Start the Service:
Start the service using
systemctl:sudo systemctl start myscript.service -
Enable the Service to Start on Boot:
To ensure that the service starts automatically on boot, enable it:
sudo systemctl enable myscript.service -
Check the Status of the Service:
To check the status of the service and see if it's running correctly:
sudo systemctl status myscript.service -
View Logs for Debugging:
To view logs for the service, which can be useful for debugging:
sudo journalctl -u myscript.service
By following these steps, you can effectively manage your Python script as a service using
systemd.