loading...

How to use multiple versions of Python

hardiksondagar profile image Hardik Sondagar ・1 min read

My system has 2.7.6 as a default python version and most of my applications runs on it, but one project that I'm working with AWS IoT requires version 2.7.9.

I will show how to run multiple versions of python using pyenv.

Prerequisite

$ sudo apt-get update
$ 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

Install pyenv

Install pyenv with one-liner provided by the automatic installer.

$ curl -L https://raw.githubusercontent.com/yyuu/pyenv-installer/master/bin/pyenv-installer | bash

Add following lines at the end of .bashrc file and restart the terminal.

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

Note : For zsh use .zshrc file.

Usage

Install python version 2.7.9.

$ pyenv install 2.7.9

List all installed python versions.

$ pyenv versions
* system (set by /home/ubuntu/.pyenv/version)
  2.7.9

Use 2.7.9 version for your project.

$ mkdir aws-iot-mqtt
$ cd aws-iot-mqtt
$ pyenv local 2.7.9

Now, verify which python version is enabled for current directory.

// Inside `aws-iot-mqtt` directory
$ python -V
Python 2.7.9
// Check version in parent directory
$ cd ..
$ python -V
Python 2.7.6

Note: Tested on Ubuntu 16.04 server edition

Discussion

pic
Editor guide
Collapse
tux0r profile image
tux0r

If you are on Windows, you can get pyenv over pip (as long as you don't plan to use Python 3 with it).

Collapse
rhymes profile image
rhymes

It's probably safer to use Windows Subsystem for Linux for that although it's not a real solution

Collapse
hardiksondagar profile image
Hardik Sondagar Author

Windows + Linux Bash = Perfect Combination

Thread Thread
tux0r profile image
tux0r

Except that it breaks your workflow because C:\ is suddenly /mnt/c/.

Collapse
tux0r profile image
tux0r

It's probably safer to use Windows Subsystem for Linux for that

Why?

Thread Thread
rhymes profile image
rhymes

Because Windows is not supported by pyenv but you can use it inside the sub system being a Linux compatible environment

Collapse
ishands profile image
Ishan Das Sharma

pipenv is a cross-platform solution to the same thing. You should check it out