Recently I had to migrate some old Python projects to another server, which required possibility to have different Python versions. PyEnv was the obvious choice for this, but turned out that instructions (even the ones from official documentation) do not work as expected — the part with PATHs and initialization scritps does not fit Ubuntu.
After some experiments I’ve found a working solution, and here it is:
1. Install binaries:
sudo apt-get install -y make build-essential libssl-dev zlib1g-dev \
libbz2-dev libreadline-dev libsqlite3-dev wget curl llvm libncurses5-dev \
libncursesw5-dev xz-utils tk-dev libffi-dev liblzma-dev python-openssl \
git
2. Install pyenv
and pyenv-virtualenv
:
git clone https://github.com/pyenv/pyenv.git ~/.pyenv
echo 'export PYENV_ROOT="$HOME/.pyenv"' >> ~/.bashrc
echo 'export PATH="$PYENV_ROOT/bin:$PATH"' >> ~/.bashrc
echo 'eval "$(pyenv init --path)"' >> ~/.bashrc
echo 'eval "$(pyenv init -)"' >> ~/.bashrc
source ~/.bashrc
git clone https://github.com/pyenv/pyenv-virtualenv.git $(pyenv root)/plugins/pyenv-virtualenv
After this, you’re ready to go. Let’s say, you need a latest Python of 3.6.* branch. Run:
pyenv install --list | grep
It will display all options that match 3.6
pattern, and at the moment the latest is 3.6.15. To install it, run:
pyenv install 3.6.15
To create a virtualenv, based on this version, run:
pyenv virtualenv 3.6.15 the_env_name
A virtualenv is created, to activate it, run:
pyenv activate the_env_name
The prompt will be prepended by currently activated environment name.
Happy coding!