Python: why should we create a virtual environment ?

Today, I would like to share with you what a virtual environment is and why we should setup a virtual environment on Python.

Problem
Assumption that you are working on two different projects: Project A & Project B.
Project A requires python 2.7 and request 2.x.
Project B requires python 3.x and request 3.x.
How should you do ?

Solution
A virtual environment is the right way to do it.
A Python virtual environment is to create an isolated environment for Python projects. Each project has its own dependencies

.Tool
virtualenv (python 2.x) or venv (built-in in python 3.x)

Prerequisite
a. Install pip
b. Install virualenv
– Python 2.x: pip install virutalenv
– Python 3.x: venv module had already installed

To create a virtual environment
mkdir your_project
cd your_project
Then,
– Python 2.x: virtualenv my_env
– Python 3.x: python3 -m venv my_env

To use the the packages/resources

  • Windows
    • my_env\Scripts\activate.bat
  • Linux:
    • $source  my_env/bin/activate
    • (my_env)$

To install the package

  • Windows: my_env\Scripts\pip.exe install package_name
  • Linux: my_env/Scripts/pip install package_name

To stop the virtual environment

  • Windows: deactivate
  • Linux: $deactivate 

To manage virtual environments

  • Purpose:
    • Organize all virtual environments in one location
    • Can create, delete or copy the environment
    • a single command to switch between environments
  • Tool: 
    • Windows: virtualenwrapper-win
    • Linux: virtualenwrapper
  • How to use

Leave a Reply

Your email address will not be published. Required fields are marked *