Search code examples
pythonpython-3.xmacospyenv

How install and use different versions of pythons on MacOS using pyenv


Starting out when I run $ which python3 I get:

/Library/Frameworks/Python.framework/Versions/3.8/bin/python3

And in my .zprofile I have:

PATH="/Library/Frameworks/Python.framework/Versions/3.8/bin:${PATH}"
export PATH

So starting out, I have 3.8 installed and it works. Now, I need to create a setup that will allow me to install and use different versions of python for different projects.

So, I tried the following:

$ brew update
$ brew install pyenv
$ pyenv version

It printed out System. So, it only sees the python 2.7 that comes with macos. Then I tried:

$ pyenv install 3.9.1
$ pyenv install 3.8.7
$ echo -e 'if command -v pyenv 1>/dev/null 2>&1; then\n  eval "$(pyenv init -)"\nfi' >> ~/.zshrc
$ source ~/.zshrc

Now, at the end of my .zshrc file I have:

if command -v pyenv 1>/dev/null 2>&1; then
  eval "$(pyenv init -)"
fi

But I still just get System when I run $ pyenv version. I know the different python versions are getting installed in ~/.pyenv/versions directory. So, what else am I supposed to do to get it to list all the versions and switch back and forth between them?


Solution

  • First off, for pyenv to work correctly, you should uninstall the Python that's in /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 and remove it from your $PATH.

    If you use pyenv to manage your Python versions, then you should not install Python in any other way. pyenv will update your path automatically as you switch Python version.

    Next, you need to set pyenv‘s default Python version by doing

    $ pyenv global 3.9.1
    

    on the command line.

    Finally, to switch Python versions, you can use

    $ pyenv local 3.8.7
    

    on the command line. Note, that setting the local Python is sticky and works on a per-directory basis. So, for each directory where you need a specific Python version, use this command once.

    For more info, see https://github.com/pyenv/pyenv/blob/master/COMMANDS.md