How do you switch between python 2 and 3, and vice versa?

rayne117 picture rayne117 · Dec 2, 2010 · Viewed 84.6k times · Source

I am reading How To Learn Python The Hard Way, which uses 2. Recently discovered Invent With Python, which uses 3.

Can I download python 3, and use it when I read Invent With Python, then switch back to python 2 when I want to read How To Learn Python The Hard Way. If so, how would I choose which version I use?

Answer

Vijay Shetty picture Vijay Shetty · Apr 12, 2016

Using 'virtualenv' you can have different isolated Python environments on a single machine. Also you can switch any-time between the different python interpreter versions.

What is virtualenv?

A Virtual Environment is an isolated working copy of Python which allows you to work on a specific project without worry of affecting other projects. It enables multiple side-by-side installations of Python, one for each project. It doesn’t actually install separate copies of Python, but it does provide a clever way to keep different project environments isolated.

How to install?

pip install virtualenv

To create virtual environment for python 2.7 :

root:~# which python2.7

/usr/bin/python2.7

root:~# which python3.4

/usr/local/bin/python3.4

You can also use a Python interpreter of your choice:

root:~# virtualenv -p /usr/bin/python2.7 Vpy27

Running virtualenv with interpreter /usr/bin/python2.7

New python executable in /root/Vpy27/bin/python2.7

Also creating executable in /root/Vpy27/bin/python

Installing setuptools, pip, wheel...done.

To begin using the virtual environment, it needs to be activated:

root:~# source Vpy27/bin/activate

The name of the current virtual environment will now appear on the left of the prompt:

(Vpy27) root:~# python -V
Python 2.7.3

Install packages as usual, for example:

(Vpy27) root:~# pip install junos-eznc    >> All pip installs done here, will be available only in this environment.

If you are done working in the virtual environment for the moment, you can deactivate it:

(Vpy27) root:~# deactivate   

To create virtual environment for python 3.4:

root:~# which python3.4

/usr/local/bin/python3.4

root:~# virtualenv -p /usr/local/bin/python3.4 Vpy34

root:~# source Vpy34/bin/activate

(Vpy34) root:~# python -V
Python 3.4.4

There is also a way to create virtual environment with already available site-packages.