pyenv / pyenv

Simple Python version management

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

running a python script in a pyenv environment with sudo or withing a systemd service

sterwen opened this issue · comments

This is not a bug more a limitation.
Haven't found a way to run a script installed in a virtual environment as sudo or from systemd.

Both sudo or systemd start from a minimal environment so the modules are not found.
sudo <script> is launched from the virtual environment

From systemd, the solution seems to activate the virtualenv for the execution, but if some scripts in the application need to run as root we are in the same problem.

Bottom line, the is always the solution to hard code everything and fully ditch pyenv for the execution environment but to distribute widely or application this is a limitation.

Description

Tested on Debian 12
Python 3.11
pyenv 2.4.0-2-ge1f07da7

Set up the running shell's environment the same way as you set up your regular shell's environment to use Pyenv prior to running the needed command.
Alternatively, if you need just a single virtualenv environment to work, just sourcng its activate prior to running the command would probably suffice.

It's not the most portable solution, but you can directly hard code the path to the python executable installed with pyenv. Here is an example for this case that I used years ago (source):

[Service]
ExecStart=/home/<user>/.pyenv/versions/3.12.3/bin/python <script>