02 October 2020

Install PyEnv if you want various Python versions on Ubuntu

One of the major issues with installing new versions of Python is that if you try removing it or try removing the existing version, it'll cause problems with the working of the operating system, because Ubuntu uses Python for many of its system functions.

As an alternative, people suggest using Anaconda or Miniconda. When I tried it, I ran into errors where the package versions installed with Anaconda conflicted with the system Python versions. At my wit's end, I finally gave PyEnv a try and it worked beautifully. (Also have a look at Poetry)
  1. sudo apt-get install -y make openssl 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 curl
  2. curl https://pyenv.run | bash
  3. Follow the instructions shown on the terminal to add commands to bashrc. If you see any warning messages, follow the advice mentioned in the message. Close terminal. Open a new one. 
  4. sudo apt-get install -y gcc make zlib1g-dev libreadline-dev libreadline8 sqlite3 libsqlite3-dev libbz2-dev python-tk python3-tk tk-dev
  5. pyenv install --list to see the latest versions of python available.
  6. pyenv install -v 3.8.3  (or install one of the latest versions 3.9 or any other, but do remember that the higher versions of Python would need higher versions of dependent libraries which may or may not be available with the version of Ubuntu you have installed)
  7. pyenv global 3.8.3
Useful commands:
  • To see which versions of pyEnv are installed: ls ~/.pyenv/versions/ or pyenv versions
  • To remove any version: pyenv uninstall 2.7.15 or rm -rf ~/.pyenv/versions/2.7.15
  • Check which is the system default version: python -V
  • To revert back to the default system python: pyenv global system
  • Commands available with pyenv: pyenv commands
  • Getting help for any of those commands: pyenv shims --help
  • Check if pip is installed: pyenv which pip
  • Set a global version: pyenv global 3.6.8
  • Set a local version for a specific application's directory: pyenv local 2.7.15
The most impressive parts of PyEnv are the ability to switch between Python versions and have separate local and global versions.
Although the next step would be to install a virtual environment using pipEnv, I didn't like it because the updates portion is poorly implemented. There's also venv you could try.

No comments: