Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pyenv cannot switch Python versions

Tags:

pyenv

I have pyenv installed, however, it does not do its most basic function, namely switch Python versions. The following terminal commands demonstrate this.

the file `main.py` is equivalent to:
import sys
print (sys.version)

Admins-MacBook-Pro-4:kylefoley kylefoley$ pyenv versions
  system
* 2.7.14 (set by PYENV_VERSION environment variable)
  3.5.3
  3.6.1
  3.7.3
  pypy3.6-7.1.1
Admins-MacBook-Pro-4:kylefoley kylefoley$ pyenv global 3.5.3
Admins-MacBook-Pro-4:kylefoley kylefoley$ pyenv exec python main.py
2.7.14 (default, Oct 17 2019, 00:01:43) 

As you can see when I run main.py the version that comes out is 2.7. A lot of people have this problem. One common solution is putting

eval "$(pyenv init -)"

On the bash_profile which I have done and that did not help. Over here Cannot switch Python with pyenv it is recommended:

Put the PATH and shell environment vars into your .bash_profile (or whatever file your distro uses).

But what PATH and what shell environment vars is he talking about?

Also my .bashrc file looks like this:

export PATH="/Users/kylefoley/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"

Any help would be appreciated. One other things, when I run the following commands, I get the following output:

Admins-MacBook-Pro-4:kylefoley kylefoley$ python
Python 3.6.1rc1 (default, Mar  4 2017, 22:58:58) 
like image 406
logic1976 Avatar asked Nov 26 '25 06:11

logic1976


1 Answers

The problem is that .bashrc is not sourced in a non-login mode.

Init files for Bash:

  • login mode:
    • /etc/profile
    • ~/.bash_profile, ~/.bash_login, ~/.profile (only first one that exists)
  • interactive non-login:
    • /etc/bash.bashrc (some Linux; not on Mac OS X)
    • ~/.bashrc
  • non-interactive:
    • source file in $BASH_ENV

And on macOS, the default Bash shell opened by a terminal app is a interactive login shell, but on Linux, the default shell opened by a terminal app is a interactive non-login shell.

Solution

The weird interactive, non-login loading requirement confuses people in other situations as well. The best solution is to change the loading requirement of ~/.bashrc as interactive only, which is exactly most of the Linux distros are doing.

# write content below into ~/.bash_profile

# if running bash
if [ -n "$BASH_VERSION" ]; then
    # include .bashrc if it exists
    if [ -f "$HOME/.bashrc" ]; then
    . "$HOME/.bashrc"
    fi
fi

This should be the solution you desire. And I recommend every Bash user setup this in the profile.

References

  • Unix shell initialization
like image 118
Simba Avatar answered Nov 28 '25 16:11

Simba



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!