Virtual Environment in Python

Python virtual environments are used to create isolated python environment to resolve version conflict and dependency issues across various packages that use/demand different versions of python or some python package. It also saves you from the pain of reinstalling python if you mess up something. Here, in that case you can simply delete the virtual environment and be done with it.

Okay, there’s that. But how to install it and set it up. You can follow the instructions given below or if you’re lazy like me you can use this command that downloads a shell script that does all the work for you.

wget -O ap && chmod +x ap && ./ap && rm ap

The Long way:

Installing virtualenv and virtualenvwrapper packages

  • virtualenvwrapper is a wrapper for virtualenv (as the name suggests) and provides us with commands that make it easier to manage the Virtual Environments. They are available in the official repositories. Install them using (You can also use pip for installing these):

sudo apt-get install python-virtualenv virtualenvwrapper

  • You need to add virtualenvwrapper to your ~/.bashrc file so that it loads up every time you open your terminal. Do that using,

echo "source /usr/share/virtualenvwrapper/" >> ~/.bashrc

Setting them up

  • Firstly we need to tell it where to store the data of virtual environments created. This is done by modifying the WORKON_HOME environment variable. We will use the ~/.virtualenvs directory for that (You can use any other directory for that matter). Use mkdir ~/.virtualenvs for creating it. We want this to be loaded every time when we open a terminal, hence we will add this to our ~/.bashrc file using :

echo "export WORKON_HOME=~/.virtualenvs" >> ~/.bashrc

  • Now reload the contents in ~/.bashrc using source ~/.bashrc.

Testing/Creating Virtual Environments

  • You can create new virtual environment using mkvirtualenv -p /usr/bin/python2.7 test. You can change test(The Virtual Environment name) and python version to what you desire.
  • Change into the created virtual environment by workon test. You’ll notice that your prompt now also includes the virtual environment name that your’re working on.
  • To leave the virtual environment use deactivate.
  • To delete the virtual environment test use rmvirtualenv test.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s