Table of Contents

Motivation

How to switch any version of Python with pyenv

Installation

  1. Confirm the default Python version.

    $ python --version
    Python 2.7.16
  2. Install pyenv by brew on macOS.

    $ brew install pyenv
  3. Define the environment variable and add pyenv init to your shell.

    export PYENV_ROOT="${HOME}/.pyenv"
    export PATH=${PYENV_ROOT}/bin:$PATH
    eval "$(pyenv init -)"
  4. See installable Python versions on pyenv.

    $ pyenv install -l
    Available versions:
    2.1.3
    2.2.3
    2.3.7
    :
    :
  5. Install a specific Python version.

    $ pyenv install 3.9.0
    :
    Installed Python-3.9.0 to /Users/xxxx/.pyenv/versions/3.9.0
  6. See the current Python version and installed versions.

    $ pyenv versions
    \* system (set by /Users/xxxx/.pyenv/version)  <=== current Python version.
      3.9.0

Switch the global Python version

Switch to the specific version from the current version as a global configuration.

$ pyenv global 3.9.0

$ pyenv versions
    system
\* 3.9.0 (set by /Users/xxxx/.pyenv/version)

$ python --version
Python 3.9.0

$ pip -V
pip 20.2.3 from /Users/xxxx/.pyenv/versions/3.9.0/lib/python3.9/site-packages/pip (python 3.9)

Switch the local Python version

Apply specific Python version to a specific directory.

$ mkdir sandbox; cd sandbox

$ pyenv versions 
\* system
    3.9.0 (set by /Users/xxxx/.pyenv/version)

$ python --version
Python 2.7.16

$ pyenv local 3.9.0

$ cat .python-version
3.9.0

$ pyenv versions
    system
\* 3.9.0 (set by /Users/xxxx/sandbox/.python-version)

$ python --version
Python 3.9.0

Isolate some packages with venv

  1. Switch to a specific Python version with pyenv.

  2. See installed packages.

    $ pip list
    Package    Version
    ---------- -------
    pip        20.3.3
    setuptools 49.2.1
  3. Create a virtual environment.

    $ python -m venv <target directory>
    
    $ ls <target directory>
    bin     include     lib     pyvenv.cfg
  4. Activate the virtual environment.

    $ source <target directory>/bin/activate
    
    (target directory name) $
  5. Install a package and confirm that it has been installed in the virtual environment.

    $ pip install selenium
    :
    Successfully installed selenium...
    
    $ pip freeze
    selenium==3.141.0
    urllib3==1.26.2
  6. Deactivate the virtual environment.

    (target directory name) $ deactivate
    
    $
  7. Some packages have been isolated between the original environment and the virtual environment.

    $ pip freeze
    $

What’s the difference between pip freeze and pip list ?