Usando o pyenv e pyenv-virtualenvwrapper para gerenciar múltiplos ambientes python

Gabriel Bellon
Conta Azul Engineering Blog
6 min readJun 18, 2020

--

Primeiramente, me apresentando, sou Gabriel Bellon faço parte do time de dados e atuo como cientista de dados na Conta Azul.
Python é a linguagem padrão dentro do time de dados, sendo usado desde para criar análise exploratórias complexas, passando por integrações e consolidações de dados utilizando o Airflow e criação de modelos preditivos utilizando diversas bibliotecas e até criando soluções internas que ajudam tanto o time de dados como toda a empresa a resolver diversos problemas.

Gerenciando diversos ambientes virtuais

Com uma infinidade de projetos e configurações, geramos um problema inicial de organizar e controlar todas as versões de python e biblioteca instaladas em cada um deles.

Uma imagem de um quadrinhos com um diagrama com vários ambientes virtuais e instalações de python totalmente bagunçado
Python Environment https://xkcd.com/1987/

Para ajudar nesse controle (e bagunça :D) utilizamos uma biblioteca que permite a gerência de múltiplas versões de python (pyenv) e um gerenciador de ambientes virtuais (virtualenvwrapper), ambos integrados.

Pyenv

Pyenv é um gerenciador criado para controlar múltiplas versões de python em um mesmo ambiente que permite com que versões distintas sejam executadas, além de se combinar com a criação de ambientes virtuais.

Instalando o pyenv

Basta seguir as recomendações do repositório oficial: https://github.com/pyenv/pyenv#basic-github-checkout

Ou utilizar um script de instalação que auxilia em algumas configurações: https://github.com/pyenv/pyenv-installer

#Executando pela instalação pura 
$ curl https://pyenv.run | bash
#Utilizando o script de instalação
$ curl -L https://github.com/pyenv/pyenv-installer/raw/master/bin/pyenv-installer | bash

Além disso é necessário configurar algumas variáveis dentro de seu interpretador de comandos (.bashrc para o bash ou .zshrc para z-shell)

#Configurando o caminho do pyenv
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
#Aqui já ativando o virtualenv para funcionar nativamente
eval "$(pyenv virtualenv-init -)"

Uma vez tendo tudo instalado, pode-se usar o comando pyenv, que deve retornar algo parecido como:

Um terminal exibindo os comandos da lib pyenv

Alguns exemplo de uso do pyenv:

  • Listar a versão corrente (system):
$ pyenv versions
> system (set by /home/gabriel/.pyenv/version)
  • Instalar a versão python 3.5.7:
$ pyenv install 3.5.7 
> Downloading Python-3.5.7.tar.xz...
> -> https://www.python.org/ftp/python/3.5.7/Python-3.5.7.tar.xz
> Installing Python-3.5.7...
> Installed Python-3.5.7 to /home/gabriel/.pyenv/versions/3.5.7
  • Listar as versões instaladas (system e 3.5.7):
$ pyenv versions
> * system (set by /home/gabriel/.pyenv/version)
> 3.5.7 (set by /home/gabriel/.pyenv/version)

O símbolo * indica a versão definida como global, que pode também pode ser verificada com o comando:

$ pyenv global
> system

Isso indica que todos os comandos pythons (pip, pip3 python, python3, etc.) serão executados pela versão system.

  • Modificando a versão global para a versão 3.5.7 e verificando a mesma:
$ pyenv global 3.5.7; pyenv versions
> system
> * 3.5.7 (set by /home/gabriel/.pyenv/version)
  • Executando os comandos python, python3 e python3.5 (irá executar a versão 3.5.7):
$ python
> Python 3.5.7 (default, Jun 21 2019, 17:36:06)
> [GCC 7.4.0] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>
> ...
$ python3
Python 3.5.7 (default, Jun 21 2019, 17:36:06)
[GCC 7.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
> >>
> ...
$ python3.5
> Python 3.5.7 (default, Jun 21 2019, 17:36:06)
> [GCC 7.4.0] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>
  • Modificando a versão global para as duas (3.57 e system) e resolvendo nessa ordem:
$ pyenv global 3.5.7 system; pyenv global
> 3.5.7
> system
  • Executando o comando python e python3.6 e python2.7:
$ python
> Python 3.5.7 (default, Jun 21 2019, 17:36:06)
> [GCC 7.4.0] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>
> ...
$ python3.6
> Python 3.6.8 (default, Jan 14 2019, 11:02:34)
> [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
> Type "help", "copyright", "credits" or "license" for more information.
>>>
> ...
$ python2.7
> Python 2.7.15+ (default, Nov 27 2018, 23:36:35)
> [GCC 7.3.0] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>>

A versão 3.5.7 é reconhecida como inicial, resolvendo o comando, sendo o comandos python3.6 e python2.7 resolvidos pela versão system

  • Invertendo as ordens das versões (system e depois 3.5.7):
$ pyenv global system 3.5.7; pyenv global
> system
> 3.5.7
  • Executando o comandos novamente python e python3 e python3.5:
$ python
> Python 2.7.15+ (default, Nov 27 2018, 23:36:35)
> [GCC 7.3.0] on linux2
> Type "help", "copyright", "credits" or "license" for more information.
> >>>
> ...
$ python3
> Python 3.6.8 (default, Jan 14 2019, 11:02:34)
> [GCC 8.0.1 20180414 (experimental) [trunk revision 259383]] on linux
> Type "help", "copyright", "credits" or "license" for more information.
> >>>
> ...
$ python3.5
> Python 3.5.7 (default, Jun 21 2019, 17:36:06)
> [GCC 7.4.0] on linux
> Type "help", "copyright", "credits" or "license" for more information.>
> >>>

A versão inicial (system) resolve os comandos pythone python3, sendo que o comando python3.5 é resolvido pela versão também definida como global (3.5.7)

Para mais detalhes, documentações e exemplos consulte o repositório oficial da ferramenta: https://github.com/pyenv/pyenv .

Virtualenvwarpper

O virtualenvwarpper é um plugin que cria alguns facilitadores e atalhos para utilizar ambientes virtuais com o python. Mais detalhes na documentação oficial: https://virtualenvwrapper.readthedocs.io/en/latest/command_ref.html.

Combinando o mesmo com o pyenv temos o pyenv-virtualenvwrapper, um plugin do pyenv que permite criar ambientes virtuais de forma rápida e prática utilizando todas as versões de python gerenciadas pelo pyenv.

Instalando pyenv-virtualenvwrapper

A instalação é realizada seguindo as recomendações do repositório oficial https://github.com/pyenv/pyenv-virtualenvwrapper

Instalando o pyenv-virtualenvwrapper , sendo que as versões de python global do pyenv precisam ter o virtualenvwrapper instalados:

#pip e pip3 caso tenha python2.7 e python3 simultaneamente.
pip install setuptools
pip install virtualenvwrapper
pip3 install setuptools
pip3 install virtualenvwrapper
# $(pyenv root) é a variável do pyenv que indica onde o mesmo está instalado.
git clone https://github.com/pyenv/pyenv-virtualenvwrapper.git $(pyenv root)/plugins/pyenv-virtualenvwrapper

É necessário modificar o arquivo de configuração de seu interpretador de comandas (bashrc para o bash ou .zshrc para z-shell) e adicionar algumas linhas antes e depois as configurações do pyenv:

#Configurações do virtualenvwrapper
export WORKON_HOME=$HOME/.virtualenvs #Pasta dos ambientes virtuais
source $HOME/.local/bin/virtualenvwrapper.sh #Script principal
#Bloco do pyenv já existente no arquivo
export PATH="$HOME/.pyenv/bin:$PATH"
eval "$(pyenv init -)"
eval "$(pyenv virtualenv-init -)"
#Explicita para o pyenv o uso do virtualenvwrapper
export PYENV_VIRTUALENVWRAPPER_PREFER_PYVENV="true"

Exemplo de uso pyenv-virtualenvwrapper

No exemplo a seguir estamos configurando a versão global do python para a miniconda3-latest, após isso é criado um virutalenv com o virtualenvwrapper (test_conda).

Voltamos a versão global do python para a system e 3.7.4, acessamos o virtualenv criado (test_conda) e verificamos que o mesmo foi criado utilizando o python da instalação do miniconda3-latest

Um novo virtualenv é criado (test_2.7) e ativado, validando que o mesmo utilizou a versão de python configurada como padrão (system)

# Listando as versões de python instaladas
$ pyenv global
> system
> 3.7.4

# Configurando como global versão miniconda3-latest
$ pyenv global miniconda3-latest
$ (miniconda3-latest)
$ python
> Python 3.7.4 (default, Aug 13 2019, 15:17:50)
> [Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> exit()

# Criando um novo ambiente virtual
$ (miniconda3-latest)
$ mkvirtualenv test_conda

# Ativando o novo ambiente virtual
$ workon test_conda
> (test_conda)
$ python
> Python 3.7.4 (default, Aug 13 2019, 15:17:50)
> [Clang 4.0.1 (tags/RELEASE_401/final)] :: Anaconda, Inc. on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> exit()
# Desativando o ambiente virtual e verificando a versão ativa
> (test_conda)
$ deactivate
$ python
> Python 2.7.16 (default, Dec 13 2019, 18:00:32)
> [GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.32.4) (-macos10.15-objc-s on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> exit()
# Criando um ambiente virtual com a versão 2.7
$ mkvirtualenv test_2.7
> New python executable in /Users/gabriel.bellon/.virtualenvs/test_2.7/bin/python
> Installing setuptools, pip, wheel...
> done.
> virtualenvwrapper.user_scripts creating /Users/gabriel.bellon/.virtualenvs/test_2.7/bin/predeactivate
> virtualenvwrapper.user_scripts creating /Users/gabriel.bellon/.virtualenvs/test_2.7/bin/postdeactivate
> virtualenvwrapper.user_scripts creating /Users/gabriel.bellon/.virtualenvs/test_2.7/bin/preactivate
> virtualenvwrapper.user_scripts creating /Users/gabriel.bellon/.virtualenvs/test_2.7/bin/postactivate
> virtualenvwrapper.user_scripts creating /Users/gabriel.bellon/.virtualenvs/test_2.7/bin/get_env_details
> (test_2.7)
> $ python
> Python 2.7.16 (default, Dec 13 2019, 18:00:32)
> [GCC 4.2.1 Compatible Apple LLVM 11.0.0 (clang-1100.0.32.4) (-macos10.15-objc-s on darwin
> Type "help", "copyright", "credits" or "license" for more information.
> >>> exit()
> (test_2.7)
$ deactivate

Uma vez com a configurações criadas e testada, agora fica prático realizar o gerenciamento de múltiplos projetos python com diferentes versões e com o uso do pyenv e do pyenv-virtualenvwrapper criar combinações de podemos criar instalações e ambientes virtuais padrões para qualquer situação de projetos.

Esses texto foi originalmente publicados no meu site pessoal em 2 artigos, (1,2). Fique a vontade para consulta-los além de compartilhar, e qualquer dúvida ou sugestões pode entrar em contato !

Espero ter ajudado a controlar melhor o seu ambiente python e até a próxima !

--

--

Nunca fui bom de fazer bios. Escrevo loucuras, devaneios e algumas coisas técnicas. Me acha aqui também: gabubellon.me