Implementations of Mutual Information (MI) and Entropy in Python
2017-06-14
Show all

A tutorial on Virtual Environments in Python

20 mins read

What Virtualenv Is

Virtualenv is a great piece of software. It allows creating virtual environments. Each of them can have a different version of Python and different sets of libraries.

While creating this tutorial I used the following tools and versions:

  • virtualenv – 1.4.8
  • Python – 2.6.5
  • Ubuntu 10.04 64 bit
  • All console programs run with UTF-8

Do I Need a Virtual Environment?

As usual: it depends. Normally you can create and use Python programs without that, but using virtual environments can help a lot.

Such a virtual environment provides many possibilities such as:

  • On production servers, it allows running applications created for different Python versions.
  • On testing servers, it allows performing many tests including:
    • Testing the installer script if that really installs all necessary libraries by checking their versions.
    • Testing applications using a different set of libraries.
    • Checking if an upgrade of a library won’t cause errors.

Basic Steps with Virtualenv

Installation

Installation is very easy. The best way is to perform a system-wide installation so all users can create, and use the virtualenv. This must be done from an administrator account. I use Ubuntu on my laptop and I will use the sudo command, on other systems that could be done some other way.

The command for installing is simple:

    sudo easy_install virtualenv

A successful command execution should print on the console something like this:

    sudo easy_install virtualenv
    Searching for virtualenv
    Best match: virtualenv 1.4.8
    Processing virtualenv-1.4.8-py2.6.egg
    Adding virtualenv 1.4.8 to easy-install.pth file
    Installing virtualenv script to /usr/local/bin

    Using /usr/local/lib/python2.6/dist-packages/virtualenv-1.4.8-py2.6.egg
    Processing dependencies for virtualenv
    Finished processing dependencies for virtualenv

Creating the First Virtual Environment

Creating a virtual environment is very easy. First of all, choose the directory where you want to create it. The best location would be your home directory.

Let’s create there a special directory where all different environments will be placed. The directory will be named virt_env. For creating this directory I’ll use the normal mkdir command:

    mkdir virt_env

Now let’s create the first virtual environment inside this directory. Normally that’s done using the command:

    virtualenv virt_env/virt1

but first, let’s talk a bit about the most useful parameters that we can pass there.

Possible Parameters for Virtualenv
  • --help or -h – A standard Unix parameter used for getting information about the program. I’ve never found any program that didn’t follow that convention so it is good to remember that.
  • –verbose or -v – The program prints a lot more information than usual, which can be useful for solving some problems.
  • –quiet or -q – Opposite to the –verbose, the program prints as less information as possible.
  • –clear – In case you want to reinstall the virtualenv in a directory where is another installation. Using this option causes deleting the previous installation, and installing a new one, so you have a clean reinstall.
  • –version – Prints only the program version. For me currently that prints 1.4.8.
  • –no-site-packages – All packages installed using easy_install are global. It means that all users have access to them, and can use them. Sometimes it can be useful but now I want to have a pure virtualized environment regardless of what I have installed in the system and in other virtual environments. Using this option allows I to create what I want – the new environment won’t use any of the system python packages. A pure clean directory without any preinstalled things.
How to Create The Virtual Environment for Python

I will change now the command shown earlier by adding some parameters. I don’t want to use any preinstalled packages from my operating system, so the command looks like this:

    virtualenv virt_env/virt1 --no-site-packages

Output for the command should be like this:

    New python executable in virt_env/virt1/bin/python
    Installing setuptools............done.

Output using the --verbose parameter is a little bit messy, so don’t use it normally. This is useful only to debug some internals when you want to know how it works or when it doesn’t work:

    virtualenv virt_env/virt1 --no-site-packages --verbose

    Creating virt_env/virt1/lib/python2.6
    Symlinking Python bootstrap modules
      Symlinking virt_env/virt1/lib/python2.6/re.pyc
      Symlinking virt_env/virt1/lib/python2.6/codecs.pyc
      Symlinking virt_env/virt1/lib/python2.6/posixpath.pyo
      Symlinking virt_env/virt1/lib/python2.6/re.py
      Symlinking virt_env/virt1/lib/python2.6/stat.py
      Symlinking virt_env/virt1/lib/python2.6/UserDict.pyc
      Symlinking virt_env/virt1/lib/python2.6/posixpath.pyc
      Symlinking virt_env/virt1/lib/python2.6/re.pyo
      Symlinking virt_env/virt1/lib/python2.6/sre_constants.pyo
      Symlinking virt_env/virt1/lib/python2.6/sre.pyc
      Symlinking virt_env/virt1/lib/python2.6/sre_constants.py
      Symlinking virt_env/virt1/lib/python2.6/genericpath.pyc
      Symlinking virt_env/virt1/lib/python2.6/sre_compile.pyo
      Symlinking virt_env/virt1/lib/python2.6/posixpath.py
      Symlinking virt_env/virt1/lib/python2.6/lib-dynload
      Symlinking virt_env/virt1/lib/python2.6/copy_reg.pyc
      Symlinking virt_env/virt1/lib/python2.6/codecs.py
      Symlinking virt_env/virt1/lib/python2.6/copy_reg.py
      Symlinking virt_env/virt1/lib/python2.6/genericpath.pyo
      Symlinking virt_env/virt1/lib/python2.6/abc.pyo
      Symlinking virt_env/virt1/lib/python2.6/warnings.pyo
      Symlinking virt_env/virt1/lib/python2.6/stat.pyc
      Symlinking virt_env/virt1/lib/python2.6/sre_parse.py
      Symlinking virt_env/virt1/lib/python2.6/fnmatch.py
      Symlinking virt_env/virt1/lib/python2.6/fnmatch.pyc
      Symlinking virt_env/virt1/lib/python2.6/_abcoll.pyc
      Symlinking virt_env/virt1/lib/python2.6/os.py
      Symlinking virt_env/virt1/lib/python2.6/os.pyo
      Symlinking virt_env/virt1/lib/python2.6/encodings
      Symlinking virt_env/virt1/lib/python2.6/warnings.py
      Symlinking virt_env/virt1/lib/python2.6/UserDict.pyo
      Symlinking virt_env/virt1/lib/python2.6/abc.pyc
      Symlinking virt_env/virt1/lib/python2.6/locale.pyc
      Symlinking virt_env/virt1/lib/python2.6/sre_parse.pyc
      Symlinking virt_env/virt1/lib/python2.6/_abcoll.py
      Symlinking virt_env/virt1/lib/python2.6/types.pyo
      Symlinking virt_env/virt1/lib/python2.6/config
      Symlinking virt_env/virt1/lib/python2.6/codecs.pyo
      Symlinking virt_env/virt1/lib/python2.6/stat.pyo
      Symlinking virt_env/virt1/lib/python2.6/locale.pyo
      Symlinking virt_env/virt1/lib/python2.6/ntpath.pyc
      Symlinking virt_env/virt1/lib/python2.6/copy_reg.pyo
      Symlinking virt_env/virt1/lib/python2.6/sre_constants.pyc
      Symlinking virt_env/virt1/lib/python2.6/genericpath.py
      Symlinking virt_env/virt1/lib/python2.6/types.py
      Symlinking virt_env/virt1/lib/python2.6/sre_compile.pyc
      Symlinking virt_env/virt1/lib/python2.6/ntpath.py
      Symlinking virt_env/virt1/lib/python2.6/os.pyc
      Symlinking virt_env/virt1/lib/python2.6/_abcoll.pyo
      Symlinking virt_env/virt1/lib/python2.6/sre_compile.py
      Symlinking virt_env/virt1/lib/python2.6/fnmatch.pyo
      Symlinking virt_env/virt1/lib/python2.6/linecache.pyc
      Symlinking virt_env/virt1/lib/python2.6/types.pyc
      Symlinking virt_env/virt1/lib/python2.6/sre.py
      Symlinking virt_env/virt1/lib/python2.6/abc.py
      Symlinking virt_env/virt1/lib/python2.6/warnings.pyc
      Symlinking virt_env/virt1/lib/python2.6/UserDict.py
      Symlinking virt_env/virt1/lib/python2.6/sre_parse.pyo
      Symlinking virt_env/virt1/lib/python2.6/linecache.pyo
      Symlinking virt_env/virt1/lib/python2.6/linecache.py
      Symlinking virt_env/virt1/lib/python2.6/locale.py
    Creating virt_env/virt1/lib/python2.6/site-packages
    Writing virt_env/virt1/lib/python2.6/site.py
    Writing virt_env/virt1/lib/python2.6/orig-prefix.txt
    Writing virt_env/virt1/lib/python2.6/no-global-site-packages.txt
    Creating parent directories for virt_env/virt1/include
    Symlinking virt_env/virt1/include/python2.6
    Creating virt_env/virt1/bin
    New python executable in virt_env/virt1/bin/python
    Changed mode of virt_env/virt1/bin/python to 0755
    Testing executable with virt_env/virt1/bin/python -c "import sys; print sys.prefix"
    Got sys.prefix result: '/home/virt/virt_env/virt1'
    Creating virt_env/virt1/lib/python2.6/distutils
    Writing virt_env/virt1/lib/python2.6/distutils/__init__.py
    Writing virt_env/virt1/lib/python2.6/distutils/distutils.cfg
    Using existing setuptools egg: /usr/local/lib/python2.6/dist-packages/virtualenv-1.4.8-py2.6.egg/virtualenv_support/setuptools-0.6c11-py2.6.egg
    Installing setuptools..........
      Processing dependencies for setuptools==0.6c11
      Finished processing dependencies for setuptools==0.6c11
    ...Installing setuptools...done.
    Installing pip-0.7.1.tar.gz
      Processing pip-0.7.1.tar.gz
      Running pip-0.7.1/setup.py -q bdist_egg --dist-dir /tmp/easy_install-xgmRQJ/pip-0.7.1/egg-dist-tmp-N5lGfG
      warning: no previously-included files matching '*.txt' found under directory 'docs/_build'
      no previously-included directories found matching 'docs/_build/_sources'
      zip_safe flag not set; analyzing archive contents...
      pip.venv: module references __file__
      pip.basecommand: module references __file__
      pip.runner: module references __file__
      pip.vcs.__init__: module references __file__
      Adding pip 0.7.1 to easy-install.pth file
      Processing dependencies for pip==0.7.1
      Finished processing dependencies for pip==0.7.1
    Writing virt_env/virt1/bin/activate
    Writing virt_env/virt1/bin/activate_this.py

Using the Virtual Python Environment

Activating the Environment

Using the virtual environment is pretty simple. First of all, you have to define what environment you want to use. So far there is just one environment but later will be more.

Let’s use this one environment. The environment directory is

    virt_env/virt1/

the command for loading this environment is:

    virt@ymon:~$ source virt_env/virt1/bin/activate

A successful execution changes the prompt, now it looks like this:

    (virt1)virt@ymon:~$

The first part of the prompt is the name of the virtual environment so it is very easy to see which environment is currently used. Of course, you can change the prompt to the previous version but I wouldn’t recommend that as it can become very messy when using more environments.

Deactivating The Current Environment

The current environment can be easily deactivated using the command

    (virt1)virt@ymon:~$ deactivate

that reverts the prompt to the previous version and now it looks like this:

    virt@ymon:~$

The deactivate command exists only when a virtual environment is active, so don’t be surprised that there isn’t any when you are outside the environment.

Installing Packages in the Environment

Checking What is Installed

For listing all installed Python packages I will use yolk. This is a simple console program that can list installed packages.

Installation is quite simple:

    sudo easy_install yolk

Usage is even simpler:

    yolk -l

Running that command outside the virtual environment shows me just 114 packages so I will not paste the whole list here.

Using the yolk in the new environment needs installing that locally, so let’s install:

    virt@ymon:~$ source virt_env/virt1/bin/activate
    (virt1)virt@ymon:~$ easy_install yolk
    Searching for yolk
    Best match: yolk 0.4.1
    Processing yolk-0.4.1-py2.6.egg
    yolk 0.4.1 is already the active version in easy-install.pth
    Installing yolk script to /home/virt/virt_env/virt1/bin

    Using /home/virt/virt_env/virt1/lib/python2.6/site-packages/yolk-0.4.1-py2.6.egg
    Processing dependencies for yolk
    Finished processing dependencies for yolk
    (virt1)virt@ymon:~$

Now I can use that locally. In the new virtual environment there aren’t much packages:

    (virt1)virt@ymon:~$ yolk -l
    Python          - 2.6.5        - active development (/usr/lib/python2.6/lib-dynload)
    pip             - 0.7.1        - active
    setuptools      - 0.6c11       - active
    wsgiref         - 0.1.2        - active development (/usr/lib/python2.6)
    yolk            - 0.4.1        - active

Installing Other Packages

Now I can install all packages normally, just in one environment. It will not touch any other packages from other environments, even the ones globally packages.

Now I will install Pylons in the environment, but first, let’s create another one to ensure that the packages are really installed just in this one.

    (virt1)virt@ymon:~$ deactivate
    virt@ymon:~$ virtualenv virt_env/virt2 --no-site-packages
    New python executable in virt_env/virt2/bin/python
    Installing setuptools............done.

OK, now there is another environment, let’s check what packages are installed there (of course after installing yolk like in the previous one):

    (virt2)virt@ymon:~$ yolk -l
    Python          - 2.6.5        - active development (/usr/lib/python2.6/lib-dynload)
    pip             - 0.7.1        - active
    setuptools      - 0.6c11       - active
    wsgiref         - 0.1.2        - active development (/usr/lib/python2.6)
    yolk            - 0.4.1        - active

Great, the list looks exactly like the previous one.

Now I just switch to the first environment and install Pylons.

    (virt2)virt@ymon:~$ deactivate
    virt@ymon:~$ source virt_env/virt1/bin/activate
    (virt1)virt@ymon:~$ easy_install Pylons

This command prints a lot in the console as it installs many other packages needed by Pylons. The last lines of the messages list look like this:

    Installed /home/virt/virt_env/virt1/lib/python2.6/site-packages/Pygments-1.3.1-py2.6.egg
    Finished processing dependencies for Pylons
    (virt1)virt@ymon:~$

And also let’s install SQLAlchemy library:

    (virt1)virt@ymon:~$ easy_install SqlAlchemy

And now let’s check the list of installed packages:

    (virt1)virt@ymon:~$ yolk -l
    Beaker          - 1.5.3        - active
    FormEncode      - 1.2.2        - active
    Mako            - 0.3.2        - active
    Paste           - 1.7.3.1      - active
    PasteDeploy     - 1.3.3        - active
    PasteScript     - 1.7.3        - active
    Pygments        - 1.3.1        - active
    Pylons          - 0.10rc1      - active
    Python          - 2.6.5        - active development (/usr/lib/python2.6/lib-dynload)
    Routes          - 1.12.1       - active
    SQLAlchemy      - 0.6.0        - active
    Tempita         - 0.4          - active
    WebError        - 0.10.2       - active
    WebHelpers      - 1.0b6        - active
    WebOb           - 0.9.8        - active
    WebTest         - 1.2.1        - active
    decorator       - 3.1.2        - active
    nose            - 0.11.3       - active
    pip             - 0.7.1        - active
    setuptools      - 0.6c11       - active
    simplejson      - 2.1.1        - active
    wsgiref         - 0.1.2        - active development (/usr/lib/python2.6)
    yolk            - 0.4.1        - active

As you can see there is installed version 0.6.0 of the SQLAlchemy library.

Great, it just works but what about the second environment? Does it have those packages also installed?

    (virt1)virt@ymon:~$ deactivate
    virt@ymon:~$ source virt_env/virt2/bin/activate
    (virt2)virt@ymon:~$ yolk -l
    Python          - 2.6.5        - active development (/usr/lib/python2.6/lib-dynload)
    pip             - 0.7.1        - active
    setuptools      - 0.6c11       - active
    wsgiref         - 0.1.2        - active development (/usr/lib/python2.6)
    yolk            - 0.4.1        - active

It seems that everything is OK, so let’s install there Pylons and check the list of installed packages:

    (virt1)virt@ymon:~$ deactivate
    virt@ymon:~$ source virt_env/virt2/bin/activate
    (virt2)virt@ymon:~$ easy_install Pylons
    [... here a lot of messages ...]
    Processing dependencies for Pylons
    Finished processing dependencies for Pylons
    (virt2)virt@ymon:~$ yolk -l
    Beaker          - 1.5.3        - active
    FormEncode      - 1.2.2        - active
    Mako            - 0.3.2        - active
    Paste           - 1.7.3.1      - active
    PasteDeploy     - 1.3.3        - active
    PasteScript     - 1.7.3        - active
    Pygments        - 1.3.1        - active
    Pylons          - 0.10rc1      - active
    Python          - 2.6.5        - active development (/usr/lib/python2.6/lib-dynload)
    Routes          - 1.12.1       - active
    Tempita         - 0.4          - active
    WebError        - 0.10.2       - active
    WebHelpers      - 1.0b6        - active
    WebOb           - 0.9.8        - active
    WebTest         - 1.2.1        - active
    decorator       - 3.1.2        - active
    nose            - 0.11.3       - active
    pip             - 0.7.1        - active
    setuptools      - 0.6c11       - active
    simplejson      - 2.1.1        - active
    wsgiref         - 0.1.2        - active development (/usr/lib/python2.6)
    yolk            - 0.4.1        - active

Great, but there is no SQLAlchemy. So let’s install that but using the previous version, which means installing version 0.5.0.

    (virt2)virt@ymon:~$ easy_install "SQLAlchemy==0.5.0"
    Searching for SQLAlchemy==0.5.0
    Reading http://pypi.python.org/simple/SQLAlchemy/
    Reading http://www.sqlalchemy.org
    Best match: SQLAlchemy 0.5.0
    Downloading http://pypi.python.org/packages/source/S/SQLAlchemy/SQLAlchemy-0.5.0.tar.gz##md5=df49f403b2db3c54aace64aebe26cf90
    Processing SQLAlchemy-0.5.0.tar.gz
    Running SQLAlchemy-0.5.0/setup.py -q bdist_egg --dist-dir /tmp/easy_install-T1eI2f/SQLAlchemy-0.5.0/egg-dist-tmp-jnaNHq
    no previously-included directories found matching 'doc/build/output'
    zip_safe flag not set; analyzing archive contents...
    sqlalchemy.databases.mysql: module MAY be using inspect.stack
    Adding SQLAlchemy 0.5.0 to easy-install.pth file

    Installed /home/virt/virt_env/virt2/lib/python2.6/site-packages/SQLAlchemy-0.5.0-py2.6.egg
    Processing dependencies for SQLAlchemy==0.5.0
    Finished processing dependencies for SQLAlchemy==0.5.0

Looks fine, lets’s check the installed version:

    (virt2)virt@ymon:~$ yolk -l | grep SQLAlchemy
    SQLAlchemy      - 0.5.0        - active

The Summary

Now I’ve got two Python environments in directories:

    virt_env/virt1/
    virt_env/virt2/

in both, there is a different version of Pylons installed.

    In the first there is SQLAlchemy 0.6.0
    In the second there is SQLAlchemy 0.5.0.

Now that’s easy to test the behavior of the same Pylons application on both versions of SQLAlchemy without any changes in configuration.

Since then I’ve changed how I work with the virtualenvs, so here is a more updated version of the tutorial. A better way of managing the environments.

In this section, I will show you how to create a Virtual Environment, manage it, install different libraries, and use different Python versions in each of them.

What The Virtualenv Really Is

Virtualenv is a very simple tool for a kind of virtualizing the Python environment. Unfortunately, this is not full virtualization. It allows you just to have a separate python executable file, along with a separate set of libraries.

It doesn’t give you a totally isolated environment. This means that you cannot fully simulate the environment you have on production servers. Usually, applications communicate with some outside world. That worlds has some databases, some webservers, and some files. Virtualenv doesn’t virtualize the outside world.

The main problem is that some Python libraries are just wrappers of files, and libraries are written in C. A good example is psycopg2, it’s a great library which just a Python wrapper to a PostgreSQL library. This is great because this way we have quite a fast Python library to connect with PostgreSQL.

However, those C libraries are compiled with the current C compiler, the other libraries you have, the database version you have installed, and the hardware architecture.

To fully simulate the production environment you should have a computer with the same architecture, operating system version, installed libraries, and programs. Usually, this is not very easy to be done. You can also use docker for that.

What Virtualenv is great for is having different Python versions and different sets of libraries. I usually have one environment for each project that I’m working on. Fortunately for my projects, the outside world doesn’t matter too much. My Python software works on the production machines without any problems, as they are quite similar to the one I’m working on. Usually, they even have the same operating system, architecture, and compiler.

This can be not the same in your case, so be careful.

Python Virtualenv Advantages

The main advantages of the Python Virtualenv are:

  • Separation of packages installations – you can use different package sets for each project.
  • Separation of python versions – you can use different python versions for each project.

Why You Really Need The Virtual Environment

There are many reasons why such software is needed and why you really should use it.

The main one is that for one project you need a different version of a Python package than you have installed on your machine, or you don’t have a system package for that. The alternatives are simple:

  • Make a system package on your own (trust me, you don’t want to do that each time you switch to a new project).
  • Install globally using e.g. pip (then you should start praying if you haven’t made your machine unresponsive).
  • Just use Virtualenv.

Building good system packages, like debs or rpms is not easy. What’s more, if you have the task of writing a Python program, you probably don’t want to spend the next couple of weeks reading through the documentation of the packages. Even if you want, I’m sure your client will not be happy about that.

On Linux you can have plenty of python programs running in the background, you can even not know about that. Check it with ps uaxf | grep python. On my Ubuntu, even the network connection manager is a Python script (I use wicd). Those scripts have their dependencies, which are packed in the system packages. If your project depends on some Python package, and you want to upgrade to a global package, then you can have a much bigger problem. This new package can be incompatible with e.g. wicd, and there is a chance that your computer can suddenly lose access to the network.

Simpler things are always better. The simplest thing would be to install that package in a local directory and change the path used for finding the packages, so this one would be found instead of the system one. This is exactly what the Virtualenv does.

Using Different Python Versions

Virtualenv also allows for different Python versions. When you build a Python Virtual Environment, then you can choose the exact Python executable file you want to use. Then there is created a separate directory for this environment, and the executable file is simply copied there. All libraries for this Virtual Environment will be installed in the same directory.

Why Not Virtualenv

Virtualenv is great. Unfortunately, it is too verbose and too complicated in a day to day work. That’s why I stopped using that a long time ago.

Virtualenv vs Virtualenvwrapper

There is something much better. Much better means that it is much easier to use, while the functionality is basically the same. It is named Virtualenvwrapper and it is a set of tools for managing Python Virtualenv operations.

How to Install Virtualenvwrapper for Python

I tried installing Virtualenvwrapper globally on my machine using the deb archive with simple:

λ ymon ~ → sudo apt-get install virtualenvwrapper

The beginning λ ymon \~ → is my current shell prompt.

Unfortunately, that didn’t work properly. It installed a couple of files, but not all magic happened, and some files were missing. Especially painful was the fact, that the virtualenvwrapper.sh and virtualenvwrapper_lazy.sh were not where they should be.

After reading through almost the whole internet, I found a solution. It was simple. I fully removed the Virtualenwrapper installed with the deb file and installed it globally using sudo pip. This is also installed in the system directories.

λ ymon ~ → sudo apt-get purge virtualenvwrapper
λ ymon ~ → sudo pip install virtualenvwrapper

And suddenly I got the two files available:

λ ymon ~ → which virtualenvwrapper.sh
/usr/local/bin/virtualenvwrapper.sh

λ ymon ~ → which virtualenvwrapper_lazy.sh
/usr/local/bin/virtualenvwrapper_lazy.sh

After this, I had to configure a couple of things. First of all, I have created a directory for the Python Virtual Environments:

λ ymon ~ → mkdir ~/.virtualenvs

I have also added an environment variable to my shell. I use zshell currently, so I added this to my ~/.zshrc. If you are using a standard shell, like bash, you need to add the configuration to your ~/.bashrc file.

export WORKON_HOME=$HOME/.virtualenvs

I also had to add a command to the ~/.zshrc to run the activation script when my shell starts.

source /usr/local/bin/virtualenvwrapper_lazy.sh

The only thing left was to log out from the current shell and start a new one.

Yes, I know that I could source a config file, or start a new shell from this one. Unfortunately, sometimes it doesn’t read all the files, and sometimes the different config files fight with each other to show who is more important. Running a brand new console window ensures me that all the configs were read and executed as they should be.

How to Create a New Virtual Environment

The Python Virtualenvwrapper provides a couple of nice commands which can be used for playing with the Python Virtual Environments.

The first is used to create a new Python Virtual Environment. The name should be chosen wisely, so you will know what the purpose of the environment is. After a couple of months, I have over twenty environments and I choose the working one only by the name.

However, for the purpose of this article, I will create an environment named test1.

λ ymon ~ → mkvirtualenv test1
New python executable in test1/bin/python
Installing Setuptools ..............................................................................................................................................................................................................................done.
Installing Pip .....................................................................................................................................................................................................................................................................................................................................done.
(test1)λ ymon ~ →

As you might notice, the command prompt changed, and now it contains the name of the Virtual Environment.

(test1)λ ymon ~ → python --version
Python 2.7.5+
(test1)λ ymon ~ →

As the Python Virtual Environment has been activated, which is indicated by the changed prompt, all the Python packages you install without using sudo are installed locally. When I call the pip command, it installs the packages in the ~/.virtualenvs/test1 directory.

Let’s check the packages we have preinstalled:

(test1)λ ymon ~ → pip freeze
argparse==1.2.1
wsgiref==0.1.2

And let’s install Django

(test1)λ ymon ~ → pip install Django
Downloading/unpacking Django
  Downloading Django-1.6.4.tar.gz (6.6MB): 6.6MB downloaded
  Running setup.py egg_info for package Django

    warning: no previously-included files matching '__pycache__' found under directory '*'
    warning: no previously-included files matching '*.py[co]' found under directory '*'
Installing collected packages: Django
  Running setup.py install for Django
    changing mode of build/scripts-2.7/django-admin.py from 644 to 755

    warning: no previously-included files matching '__pycache__' found under directory '*'
    warning: no previously-included files matching '*.py[co]' found under directory '*'
    changing mode of /home/szymon/.virtualenvs/test1/bin/django-admin.py to 755
Successfully installed Django
Cleaning up...

And now the installed packages are:

(test1)λ ymon ~ → pip freeze
Django==1.6.4
argparse==1.2.1
wsgiref==0.1.2

How to Log Out of a Python Virtual Environment

If you want to deactivate the current virtual environment, you can use the command deactivate (that’s exactly like in pure virtualenv):

(test1)λ ymon ~ → deactivate
λ ymon ~ →

As you can see, the environment name disappeared from the prompt.

How to Use a Python Virtual Environment

For activating an existing Python Environment you can use the command workon:

λ ymon ~ → workon test1
(test1)λ ymon ~ →

If you write just workon and press TAB, then you should see the list of all available virtual environments.

How to Remove a Python Virtual Environment

You can remove the virtual environment using the command rmvirtualenv. Beware, it removes the whole directory in your virtual environments directory.

    (test1)λ ymon ~ → rmvirtualenv test1
    Removing test1...
    ERROR: You cannot remove the active environment ('test1').
    Either switch to another environment, or run 'deactivate'.

You cannot remove an environment you are using, so let’s deactivate it first and then remove it.

(test1)λ ymon ~ → deactivate
λ ymon ~ → rmvirtualenv test1
Removing test1...
λ ymon ~ →

How to Usee Different Python Versions

The environment I’ve already created is using my default python, which is:

(test1)λ ymon ~ → python --version
Python 2.7.5+

Imagine that I want to use a different one, let’s use Python 3.3. First of all, I need to find the binary file:

(test1)λ ymon ~ → which python3.3
/usr/bin/python3.3

Then I need to remove my current Virtual Environment (deactivating it first):

(test1)λ ymon ~ → deactivate
λ ymon ~ → rmvirtualenv test1
Removing test1...

Now I can create a new virtual environment with the same name, but using Python3.3.

λ ymon ~ → mkvirtualenv test1 -p /usr/bin/python3.3
Running virtualenv with interpreter /usr/bin/python3.3
Using base prefix '/usr'
New python executable in test1/bin/python3.3
Also creating executable in test1/bin/python
Installing Setuptools ..............................................................................................................................................................................................................................done.
Installing Pip .....................................................................................................................................................................................................................................................................................................................................done.

Let’s just check if I really have this python version in my new environment:

(test1)λ ymon ~ → python --version
Python 3.3.2+

And let’s install Django once again

(test1)λ ymon ~ → pip install Django
Downloading/unpacking Django
  Downloading Django-1.6.4.tar.gz (6.6MB): 6.6MB downloaded
  Running setup.py egg_info for package Django

    warning: no previously-included files matching '__pycache__' found under directory '*'
    warning: no previously-included files matching '*.py[co]' found under directory '*'
Installing collected packages: Django
  Running setup.py install for Django
    changing mode of build/scripts-3.3/django-admin.py from 644 to 755

    warning: no previously-included files matching '__pycache__' found under directory '*'
    warning: no previously-included files matching '*.py[co]' found under directory '*'
    changing mode of /home/szymon/.virtualenvs/test1/bin/django-admin.py to 755
Successfully installed Django
Cleaning up...

Check the installed libraries:

(test1)λ ymon ~ → pip freeze
Django==1.6.4
WCommand
Installing Virtual Environmentsudo easy_install virtualenv
Create a virtual environmentvirtualenv virt_env/virt1
Activating an environmentsource virt_env/virt1/bin/activate
Deactivating the current environment(virt1)virt@ymon:~$ deactivate

Source:

http://www.simononsoftware.com/virtualenv-tutorial/

Amir Masoud Sefidian
Amir Masoud Sefidian
Machine Learning Engineer

Comments are closed.