Working with Python Virtual environment on Ubuntu

Virtual environment (virtualenv) helps us have different python versions & different python libraries and their versions installed on our system in isolated environment (environment in this case is basically a folder/directory) without affecting our global system python version & its libraries.

Installing python virtual environment is not too difficult on your system.
Just open the terminal ( Press ctrl+alt+t in Ubuntu. You may have to check the key combination for your distro) and fire the command

pip install virtualenv
this will install virtual environment on your system, and provide you with a virtualenv command
Now we can create a folder for your python projects,
which will give you an environment to work on,
isolated from the system.
Type this on your terminal
virtualenv my_virtual_env_folder_name
You can also provide a python version to use in your project like this:
virtualenv -p /usr/bin/python2.7 my_virtual_env_folder_name
If you check this folder, it should have a few directories like these:
(Note: `my_virtual_env_folder_name` in my case is `test`)
ls -lsh my_virtual_env_folder_name/
Enter into the folder,
cd my_virtual_env_folder_name
And activate the virtual environment.
source bin/activate
This will change your current python environment & set it to this folder `my_virtual_env_folder_name`
So now that we have activated the virtual environment, we can see it on the terminal.
This shows you that a virtual environment has been activated in the terminal,
by showing the name of the virtual environment, like this:
And now everything you install with `pip` or `easy_install` should be installed, in the
my_virtual_env_folder_name/lib/pythonX.X/site-packages folder
{X.X denotes a version of python, like, 2.7, 3.4 etc}
For eg.
pip install requests
pip install lxml
Those above 2 packges “requests” and “lxml” will be installed in the local environment and not the global site-packages and dist-packages folder, which can be found at these locations
So that’s how you work on isolated python environments.
To come out of the virtual environment, you can type deactivate on the terminal and exit it, like this
This will deactivate your python environment & set terminal to global default values.

Author: Admin

Hello Friends, welcome to I am the Admin of the site. I have worked as a software programmer for 7 years. I have started this site to learn as well as share whatever little knowledge i have gained over the period of time. If you wish to contact me, you can drop in an email to: admin[AT]hackerdays[DOT]com or you can also use the contact page. Thank you and I'll see you around.

Let us know your thoughts: