For the starter (this is the opening post for the devopspy.com) let’s start with something basic, something confusing, something you see in almost every python code example i.e. virtual environment.
Python is an interpreted language, and for development all we need is a Python interpreter (included in Linux based OS – for Windows can be installed using the provided .msi). Like other programming languages Python has its own way of enhancements i.e. to use functionality not there by default, all we have to do is install the package, using any installation utility – pip (most common way), easy_install, or manual installation. These installed packages may termed as the requirements or the dependencies. These dependencies vary for every project – to get a project working all we need is the environment setup ( i.e. Python and the dependencies installed).
What is a virtual environment ?
is basically a separate Python interpreter with its own set of installed packages. As mentioned above the Python interpreter along with the installed packages make the environment – so we can have multiple Python environments on a single machine, the environments other the default are termed as virtual environment, which we need to create and activate before we can use (demonstrated later).
Why we need it ?
- There may be projects with conflicting dependencies i.e. Project 1 requires numpy version 1.2, while Project 2 requires the latest 1.11.
- There are packages which have other packages as their dependencies – usually install the latest version, and you may already have an older version of a dependency for some of your project. You can install and test such package in a virtual environment e.g. pandas installs/upgrades 3 4 other packages.
Setup and a simple Example:
$ sudo pip install virtualenv
Make a new directory to keep virtual environment (optional – just a good practice):
$ mkdir python-venvs
$ cd python-venvs
$ cd python-venvs
Create the new environment:
$ virtualenv venv_project1
Activating the virtualenv:
The above command will install a standalone version of Python, as well as pip, into an isolated directory structure. It’s a good practice to name the virtual environments descriptively. A directory will be created with the specified name, to install new packages and work inside the virtual environment you need to activate it:
$ source venv/bin/activate
Once activated you’ll see the name of the environment in parenthesis before the dollar sign (as in the above screenshot).
once done working in the virtualenv we can exit by deactivating it: