Working with multiple Python environments

With the ample use of Python in applications all over, it is a common requirement that different applications need different combinations & conflicting versions of Python modules. Rather than having separate (real or virtual) machines with different installations for the different applications, it can be simply achieved using the Python’s virtualenv module. Here’s a quick summary of how to do it in Linux.

Install the python-virtualenv package, either using the package installer, or using pip of the desired python version:

$ sudo pip3 install virtualenv

Create a directory with the desired virtual environment, with or without the system wide installed packages, and the desired python version, as follows:

$ virtualenv --system-site-packages -p python3 ./venv

Or,

$ virtualenv --no-site-packages -p python3 ./venv

Here, venv (in the current directory) is the directory created with the desired virtual environment. Now, time to activate the virtual environment:

$ . ./venv/bin/activate

Now onwards, this shell’s prompt would be prefixed by (venv) indicating the virtual environment it is using. Whatever local done on this shell is specific only to this virtual environment, it being stored in this virtual environment’s directory. So, whatever pip installs (w/o sudo) are required for an application to run, can be done here independent of any external environment – even independent of the system wide installed packages, in case the virtual environment was created without them. All such installs would be local only to this environment without affecting the external environment.

Now the desired application, needing this environment, may be run in this environment.

Once done with the virtual environment, it can be deactivated as follows:

(venv) $ deactivate

It can be activated & deactivated as & when desired. Why just one? One may have any number of different virtual environments created and activated in parallel, just using separate directories and on separate shells – no need of separate machines.

Anil Kumar Pugalia (123 Posts)

The author is a hobbyist in open source hardware and software, with a passion for mathematics, and philosopher in thoughts. A gold medallist from the Indian Institute of Science, Linux, mathematics and knowledge sharing are few of his passions. He experiments with Linux and embedded systems to share his learnings through his weekend workshops. Learn more about him and his experiments at https://sysplay.in.


   Send article as PDF   

Leave a Reply

Your email address will not be published. Required fields are marked *