To use a specific pyenv environment in a systemd service, you'll need to provide the path to the desired Python interpreter in the virtual environment and set the environment variable PATH accordingly in the service file.
Here's a step-by-step guide to crafting a systemd service file that uses a pyenv virtual environment:
- Find the path to the desired Python interpreter in the virtual environment.
You can do this by running the following command (replace <your_virtualenv> with the name of your virtual environment):
$ pyenv which python -p <your_virtualenv>
This will output the path to the Python interpreter within the virtual environment, for example:
/home/user/.pyenv/versions/<your_virtualenv>/bin/python
- Create a systemd service file (e.g., your_service.service) in /etc/systemd/system/ or ~/.config/systemd/user/ directory with the following content:
[Unit]
Description=Your Service Description
After=network.target
[Service]
User=<your_user>
Group=<your_group>
WorkingDirectory=<path_to_your_working_directory>
Environment="PATH=/home/user/.pyenv/versions/<your_virtualenv>/bin:/home/user/.pyenv/shims:/home/user/.pyenv/bin:$PATH"
ExecStart=/home/user/.pyenv/versions/<your_virtualenv>/bin/python <path_to_your_script.py>
[Install]
WantedBy=multi-user.target
Replace the following placeholders with your specific values:
- <your_user>: Your user name.
- <your_group>: Your group name.
- <path_to_your_working_directory>: The working directory for your script.
- <your_virtualenv>: The name of your virtual environment.
- <path_to_your_script.py>: The path to your Python script.
- Reload the systemd manager configuration:
Reload the systemd manager configuration:
- Enable and start the service:
$ sudo systemctl enable your_service.service
$ sudo systemctl start your_service.service
- Check the status of the service:
$ sudo systemctl status your_service.service