Skip to content

Instantly share code, notes, and snippets.

@ganindu7
Last active April 18, 2023 08:33
Show Gist options
  • Save ganindu7/eeef3b45f48764cee7841e81a652931b to your computer and use it in GitHub Desktop.
Save ganindu7/eeef3b45f48764cee7841e81a652931b to your computer and use it in GitHub Desktop.
Using a virtual python environment within a service.

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:

  1. 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
  1. 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.
  1. Reload the systemd manager configuration:
Reload the systemd manager configuration:
  1. Enable and start the service:
$ sudo systemctl enable your_service.service
$ sudo systemctl start your_service.service

  1. Check the status of the service:
$ sudo systemctl status your_service.service

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment