How to run Python script as a service on Ubuntu 22
To run a Python script as a service on Ubuntu, you can use systemd, which is the standard system and service manager for Linux. Here’s a general outline of how you can achieve this.
- Write your Python script:
Create your Python script that you want to run as a service. For example, let’s say your script is named `my_script.py`. - Create a systemd service file:
Create a systemd service file to manage your Python script. Here’s an example of what it might look like:
[Unit]
Description=My Python Script
[Service]
User=<your_username>
WorkingDirectory=/path/to/your/script
ExecStart=/usr/bin/python3 /path/to/your/script/my_script.py
Restart=always
[Install]
WantedBy=multi-user.target
Replace `<your_username>` with your actual username and `/path/to/your/script` with the actual path to your Python script.
3. Move the service file to the systemd directory:
Save the above content into a file named `my_script.service` and move it to the systemd directory `/etc/systemd/system/`.
4. Reload systemd:
After creating or modifying a systemd service file, you need to reload systemd for it to recognize the changes. Run:
sudo systemctl daemon-reload
5. Start and enable the service:
sudo systemctl start my_script
sudo systemctl enable my_script
Now your Python script should be running as a service on your Ubuntu system. You can check the status of the service using `systemctl status my_script`. Any output from your script will be logged to the system journal and can be viewed using `journalctl -u my_script`.
sudo systemctl status my_script