Skip to Content

Python virtual environment on Ubuntu

Posted on 2 mins read

I had some mess around the process of installing those tools on my laptop running Ubuntu, so my decision was to write and explain everything step by step just in a case for the memo and probably a useful post for anyone as well.

Who are those lads?

If you are not an Ubuntu user, you should better read this Presentation: pip and virtualenv.

The main problem in getting that stuff work properly — is not fresh enough package versions out the Ubuntu repository. To resolve the issue I have followed these steps:

Firstly let’s install necessary packages (build-essential is not that much required, but I am sure one day you will need it)

$ sudo apt-get install python-setuptools python-dev build-essential

The second step is to install newer version of pip (easy_install is kinda crappy, but we use it once)

$ sudo easy_install pip

Now using pip, we are getting the most important things (new version of pip has uninstall command, so you can clean up everything you’ve installed)

$ sudo pip install virtualenv virtualenvwrapper

Creating directory for our virtual environments

$ mkdir ~/.virtualenvs

Configuring bash to work with a virtualenvwrapper (add these lines to the end of ~/.bashrc (or ~/.zshrc) and proceed with relogin)

export WORKON_HOME=$HOME/.virtualenvs
source /usr/local/bin/virtualenvwrapper.sh
export PIP_VIRTUALENV_BASE=$WORKON_HOME

Done. You can work within virtual environments from now on and use pip for installing libs and applications without affecting system wide (you have already read pip documentation, right?)

$ mkvirtualenv myfirstenv
(myfirstenv)$ pip install markdown
(myfirstenv)$ deactivate

Now you can try to load some module you got with pip in virtual environment within system wide python interactive shell and figure out that module woun’t be found. To work with virtualenv again, simply type:

$ workon myfirstenv

To create completely isolated environment from system wide site-packages:

$ mkvirtualenv isolatedenv --no-site-packages
$ workon isolatedenv

NOTE: To prevent getting errors when installing pysqlite with pip, do the following:

$ sudo apt-get install libsqlite3-dev

If you need to create snapshot with virtual environment libs, to use it as requirements in another virtual environment, use freeze command:

$ workon myvirtualenv
(myvirtualenv)$ pip freeze > requirements.txt
(myvirtualenv)$ deactivate
$ workon myanothervirtualenv
(myanothervirtualenv)$ pip install -r requirements.txt

Cheers! :)

comments powered by Disqus