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 | [Unit] | 
If you’re using a virtual environment, you need to activate it inside the service: 
For example:
| 1 | [Unit] | 
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 | ● my_python_app.service - My Python Application | 
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
