DEV Community

Hardik Sondagar
Hardik Sondagar

Posted on

How to use multiple versions of Python

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
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

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 -)"
Enter fullscreen mode Exit fullscreen mode

Note : For zsh use .zshrc file.

Usage

Install python version 2.7.9.

$ pyenv install 2.7.9
Enter fullscreen mode Exit fullscreen mode

List all installed python versions.

$ pyenv versions
* system (set by /home/ubuntu/.pyenv/version)
  2.7.9
Enter fullscreen mode Exit fullscreen mode

Use 2.7.9 version for your project.

$ mkdir aws-iot-mqtt
$ cd aws-iot-mqtt
$ pyenv local 2.7.9
Enter fullscreen mode Exit fullscreen mode

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
Enter fullscreen mode Exit fullscreen mode

Note: Tested on Ubuntu 16.04 server edition

Top comments (7)

Collapse
 
rhymes profile image
rhymes • Edited

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

Windows + Linux Bash = Perfect Combination

Collapse
 
sadpixel profile image
Ishan

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

 
rhymes profile image
rhymes • Edited

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