Tuesday, April 21, 2020

Using pyenv for managing multiple python versions

Reference: https://realpython.com/intro-to-pyenv

Working on projects that require different python versions... pyenv can help manage the multiple python versions for each project by installing multiple python versions locally or even makes working with virtualenv easier (no need to activate and deactivate every time when we switch into and out of a project).

Install pyenv on ubuntu:

$ curl https://pyenv.run | bash

Add these lines to .bashrc or .zshrc

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

Now restart your current shell:

$ exec $SHELL

Using pyenv:

pyenv installs all python versions under ~/.pyenv.

$ pyenv install --list | grep " 3\.[678]"

$ pyenv install -v 3.8.2

The above command will install python version 3.8.2

➜  ~ pyenv versions                       
* system (set by /home/rwatsh/.pyenv/version)
  3.8.2
➜  ~ pyenv which python
/usr/bin/python

As seen above, currently the system's python is active.
To change to the new python we installed:

➜  ~ pyenv global 3.8.2

➜  ~ pyenv which python
/home/rwatsh/.pyenv/versions/3.8.2/bin/python

➜  ~ pyenv versions 
  system
* 3.8.2 (set by /home/rwatsh/.pyenv/version)

➜  ~ python3 -V     
Python 3.8.2


The pyenv which python command shows that python 3.8.2 is installed under pyenv root directory ($HOME/.pyenv). Pyenv builds python from source and installs it under its root directory. 

Creating virtualenv via pyenv:

➜  pyenv virtualenv 3.8.2 myproj
pyenv-virtualenv: `/home/rwatsh/.pyenv/versions/myproj' already exists.

Then in your project directory run:

➜  pyenv local myproj           
(myproj) ➜  myproj 

This will use the virtualenv under your local project directory. It creates a .python-version file to track the virtualenv being used in the project directory.

(myproj) ➜  cat .python-version 
myproj

(myproj) ➜  pyenv which python 
/home/rwatsh/.pyenv/versions/myproj/bin/python


Since we added eval "$(pyenv virtualenv-init -)" to run in your shell virtualenv associated with the project directory will automatically be activated when we cd to that directory and deactivated when we move out of it.

We can also manually activate or deactivate as:
$ pyenv activate 
$ pyenv deactivate

Thus, with pyenv we can:

  • Install multiple versions of Python
  • Switch between the installed versions
  • Use virtual environments with pyenv
  • Activate different Python versions and virtual environments automatically

No comments:

Popular micro services patterns

Here are some popular Microservice design patterns that a programmer should know: Service Registry  pattern provides a  central location  fo...