> ## Documentation Index
> Fetch the complete documentation index at: https://docs.ahmadraza.in/llms.txt
> Use this file to discover all available pages before exploring further.

# Systemctl service python

# 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`.

   ```bash theme={null}
   sudo nano /etc/systemd/system/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:

   ```ini theme={null}
   [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.target
   ```

   * `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.

   ```bash theme={null}
   sudo systemctl daemon-reload
   ```

4. **Start the Service:**

   Start the service using `systemctl`:

   ```bash theme={null}
   sudo systemctl start myscript.service
   ```

5. **Enable the Service to Start on Boot:**

   To ensure that the service starts automatically on boot, enable it:

   ```bash theme={null}
   sudo systemctl enable myscript.service
   ```

6. **Check the Status of the Service:**

   To check the status of the service and see if it's running correctly:

   ```bash theme={null}
   sudo systemctl status myscript.service
   ```

7. **View Logs for Debugging:**

   To view logs for the service, which can be useful for debugging:

   ```bash theme={null}
   sudo journalctl -u myscript.service
   ```

> By following these steps, you can effectively manage your Python script as a service using `systemd`.
