How to use virtualenv for Python

Virtualenv is used in python to separate the python used for your project and the one that is in your OS. This also includes the pypi packages. Please take note that i am using Linux mint for this how-to, but other ubuntu variant or linux distro should have no problem.

The way i am using virtualenv is to ensure i don’t confuse myself with system-wide python and the one that i am using for development. A while ago, i tend to run python 3.* with command “python3” which is a temporary solution for development.

First, you need virtualenv installed, you may use pip as follow (from python version 3.4 onwards virtualenv is bundled with the standard library)

(to install to user only)

pip install virtualenv --user

(to install to system-wide)

sudo pip install virtualenv

i am going to test virtualenv in my workspace folder

cd workspace

next lets make a new folder called “python3_test” and enter it

mkdir python3_test
cd python3_test

next we specify the python version we are going to use. Find the location by using “which” command, here are some hints;

which python
which python3
which python3.5

i am going to use python 3.5 so in the “python3_test” folder i am going to generate a virtualenv using python3.5 in a folder called env

virtualenv -p /usr/bin/python3.5 env

now we can test the python version

python — version
Python 2.7.12
which python

what? but why? well using virtualenv you need to activate is first.

source env/bin/activate

now we check our python version

python — version
Python 3.5.2

nice! now you can try to deactivate the virtualenv and try to check the python version

python — version
Python 2.7.12

yep, it works!

*Important: every time you want to use virtualenv in a folder, you need to use “source env/bin/activate”

If you are afraid you might forgot to run “source env/bin/activate” every time you enter the directory, then continue reading.

We are going to use autoenv ( Install autoenv as follow;

git clone git:// ~/.autoenv
echo ‘source ~/.autoenv/’ >> ~/.bashrc

.bashrc might differ from one linux distro to another. 
then, in our “python3_test” folder, we create a .env file as follow

echo -e “source env/bin/activate \necho ‘Virtualenv activated’” > .env

now lets test the autoenv


if deactivate command is not found, no worries, it means virtualenv is already deactivated

go up one folder

cd ..

then enter our python3_test folder

cd python3_test/

then you find this warning

autoenv: WARNING:
autoenv: This is the first time you are about to source /home/ruler/workspace/python3_test/.env:

type “y” to allow, and check your python version

python — version
Python 3.5.2
which python