Setting Up systemd on Linux

Step 1: Find the Full Path of Python

which python3

Example output: /usr/bin/python3

You will need this path later.

Step 2: Create a Systemd Service File

1. Open a new service file using nano (or any text editor):

sudo nano /etc/systemd/system/my_python_app.service

2. Add the following content to the file, replacing placeholders with actual values:

1
2
3
4
5
6
7
8
9
10
11
12
13
[Unit]
Description=My Python Application
After=network.target

[Service]
ExecStart=/usr/bin/python3 /path/to/your_script.py
WorkingDirectory=/path/to
Restart=always
User=ubuntu
Environment="PYTHONUNBUFFERED=1"

[Install]
WantedBy=multi-user.target

If you’re using a virtual environment, you need to activate it inside the service:

For example:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
[Unit]
Description=OmniParser Manager
After=network.target

[Service]
WorkingDirectory=/home/ubuntu/my_app
ExecStart=/home/ubuntu/my_app/.venv/bin/python /home/ubuntu/my_app/app.py
Restart=always
User=ubuntu
Environment="PYTHONUNBUFFERED=1"
StandardOutput=append:/home/ubuntu/my_app/logs.txt
StandardError=append:/home/ubuntu/my_app/errors.txt

[Install]
WantedBy=multi-user.target

Explanation of Each Section:

Unit

Description: A short description of the service.

After=network.target: Ensures the service starts after the network is available.

Service

ExecStart: The full path to Python and your script.

WorkingDirectory: The directory where the script is located.

Restart=always: Automatically restarts the service if it crashes.

User=ubuntu: The user under which the service runs (change this if needed).

Environment=”PYTHONUNBUFFERED=1”: Ensures real-time logging (optional).

Install

WantedBy=multi-user.target: Ensures the service starts on boot.

3. Save and exit (Ctrl + X, then Y, then Enter).

Step 3: Reload systemd to Apply Changes

sudo systemctl daemon-reload

Step 4: Enable the Service (So It Starts on Boot)

sudo systemctl enable my_python_app

Step 5: Start the Service

sudo systemctl start my_python_app

Step 6: Check the Status of the Service

sudo systemctl status my_python_app

If running successfully, you should see output like this:

1
2
3
● my_python_app.service - My Python Application
Loaded: loaded (/etc/systemd/system/my_python_app.service; enabled)
Active: active (running) since ...

Step 7: Stop or Restart or Disable the Service

sudo systemctl stop my_python_app

sudo systemctl restart my_python_app

sudo systemctl disable my_python_app

Step 8: View Logs for Debugging

journalctl -u my_python_app -f