Depending on your particular use-case this may or may not solve your problem, but this wasn't yet mentioned here. Say, you want to run a Python script that was installed in your virtual environment, and you need to setuid(0)
it, i.e. you want to run it as superuser. Say, your script is called myscript.py
, then, you can do it like this:
(.venv) $ sudo -E env PATH=$PATH ./myscript.py
Explanation
(.venv) $
is the shell's prompt, you don't need to type it, it just shows that you are currently using some virtual environment, and you are not a privileged user.
sudo -E
will tell sudo
that when starting a process, it needs to copy the environment variables from your current shell environment. So, if you have any extra variables defined in .venv/bin/activate
script, they should stick around while you are root
.
env PATH=$PATH
when using sudo -E
not all environment variables are preserved, specifically, and most importantly, the PATH
may be removed. The specifics of this behavior will depend on your sudoers file. This, however, will circumvent whatever's written in sudoers file, as it will copy the PATH
explicitly into environment sudo
creates for the new process. This is important because when your system resolves shebang comment in your myscript.py
, it will look in the PATH
variable, and the first directory to match the requirement for interpreter will be used. venv
on the other hand, sets up the shell environment in such a way that the directory containing the symlink to the chosen Python interpreter appears first, thus causing system to locate the desired Python before any other Pythons on system path.