Search code examples
pythoncentospyenv

Pyenv not shows all version when used as sudo


I installed 3.5.2 and 3.5.3 version using pyenv.

# pyenv versions
* system (set by /usr/local/pyenv/version)
  3.5.2
  3.5.3

But, when I run this command as sudo (not login as root) it not gives me all versions.

$ sudo /usr/local/bin/pyenv versions
* system (set by /root/.pyenv/version)

I tried using setting the PYENV_ROOT path, but that also not works.

$ export PYENV_ROOT=/usr/local/pyenv/
$ sudo /usr/local/pyenv/bin/pyenv versions
* system (set by /root/.pyenv/version)

I already have path set in .bash_profile in myuser

$ cat ~/.bash_profile
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin

export PATH
export PYENV_ROOT=/usr/local/pyenv/
export PATH="/usr/local/pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

Also set in root user

$ sudo cat /root/.bash_profile
# .bash_profile

# Get the aliases and functions
if [ -f ~/.bashrc ]; then
    . ~/.bashrc
fi

# User specific environment and startup programs

PATH=$PATH:$HOME/bin

export PATH
export PYENV_ROOT=/usr/local/pyenv/
export PATH="/usr/local/pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

I am using centos

$ cat /etc/issue
CentOS release 6.9 (Final)

Solution

  • $ export PYENV_ROOT=/usr/local/pyenv/
    $ sudo /usr/local/pyenv/bin/pyenv versions
    

    This doesn't work because PYENV_ROOT won't be passed to the environment in sudo. Try this:

    $ sudo PYENV_ROOT=/usr/local/pyenv/ /usr/local/pyenv/bin/pyenv versions
    

    or this:

    $ export PYENV_ROOT=/usr/local/pyenv/
    $ sudo -E /usr/local/pyenv/bin/pyenv versions
    

    -E will make the environment variables pass to pyenv. In the man page of sudo:

     -E, --preserve-env
                 Indicates to the security policy that the user wishes to preserve their existing environment variables.  The security policy may return an error if the user does not have permission to
                 preserve the environment.
    
     --preserve-env=list
                 Indicates to the security policy that the user wishes to add the comma-separated list of environment variables to those preserved from the user's environment.  The security policy may
                 return an error if the user does not have permission to preserve the environment.
    

    The .bash_profile in root doesn't work because sudo won't load it in this case. You can refer to this if you prefer to write the config in .bash_profile.