Table of Contents
Motivation
- want to switch major version of Python (i.e. between Python 2 and Python 3).
- want to switch minor version of Python (i.e. between Python3.A and Python3.B).
- want to isolate some packages for every project.
- don’t want to construct in vain a new docker container for each Python project.
How to switch any version of Python with pyenv
Installation
Confirm the default Python version.
$ python --version Python 2.7.16
Install pyenv by
brew
on macOS.$ brew install pyenv
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 -)"
See installable Python versions on pyenv.
$ pyenv install -l Available versions: 2.1.3 2.2.3 2.3.7 : :
Install a specific Python version.
$ pyenv install 3.9.0 : Installed Python-3.9.0 to /Users/xxxx/.pyenv/versions/3.9.0
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
Switch to a specific Python version with pyenv.
See installed packages.
$ pip list Package Version ---------- ------- pip 20.3.3 setuptools 49.2.1
Create a virtual environment.
$ python -m venv <target directory> $ ls <target directory> bin include lib pyvenv.cfg
Activate the virtual environment.
$ source <target directory>/bin/activate (target directory name) $
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
Deactivate the virtual environment.
(target directory name) $ deactivate $
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
?
pip list
shows the list of package names and versions in the environment andpip freeze
shows them but leaves out some internal packages like asetuptools
.pip freeze > requirements.txt
outputs the list of packages names vs versions torequirements.txt
and they can be installed in bulk bypip install -r requirements.txt
.