HighSkill

Managing Python Versions and Virtual Environments using pyenv

Managing Python Versions and Virtual Environments using pyenv

pyenv is an invaluable tool for developers who need to manage multiple Python versions seamlessly. It simplifies the development process by offering various plugins, such as pyenv-virtualenv, which enhances virtual environment management, including support for conda environments.

Note for Windows Users: pyenv does not natively support Windows. Instead, use the pyenv-win fork for Windows compatibility.

Installing pyenv

1. Install Required Python Build Dependencies

Before installing pyenv, ensure you have the necessary build dependencies for your operating system.

Mac OS X:

brew install openssl readline sqlite3 xz zlib

Ubuntu/Debian/Mint:

sudo apt-get update
sudo apt-get install make build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm \
libncursesw5-dev xz-utils tk-dev libxml2-dev libxmlsec1-dev libffi-dev liblzma-dev

Alpine:

apk add --no-cache git bash build-base libffi-dev openssl-dev bzip2-dev zlib-dev readline-dev sqlite-dev 

2. Install pyenv

The quickest way to install pyenv along with some popular plugins is through the pyenv-installer:

curl https://pyenv.run | bash

After the installation, restart your shell to apply the path changes:

exec $SHELL

3. Update pyenv

To keep pyenv up to date, use:

pyenv update

4. Switch Between Python Versions

To switch between different Python versions:

  • pyenv local 3.3.3 - Sets Python 3.3.3 in the current directory.
  • pyenv global 2.7.3 - Sets Python 2.7.3 globally across all directories.

5. Manage Virtual Environments and Python Versions

  • pyenv virtualenv 3.3.3 virtual-env-name - Creates a virtual environment named virtual-env-name using Python 3.3.3.
  • pyenv virtualenvs - Lists all created virtual environments.
  • pyenv activate virtual-env-name - Activates the specified virtual environment.
  • pyenv deactivate - Deactivates the current virtual environment.

Uninstalling pyenv

If you need to uninstall pyenv, it's straightforward. The pyenv executable is located in $PYENV_ROOT, which defaults to ~/.pyenv. To remove it:

rm -fr ~/.pyenv

Additionally, clean up your .bashrc file by removing the following lines:

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

Conclusion

In summary, pyenv is an efficient tool for managing multiple Python versions and virtual environments on a single machine. Its simplicity and range of features, including the pyenv-virtualenv plugin, make it an essential tool for Python developers.