Python Virtual Environment

  • Python virtual environments create a virtual installation of Python inside a project directory.

  • Benefit of a virtual environment:

    • Users can install and different Python packages for each virtual environment (and for the project)

    This allows users to install packages and modify their Python environment without fear of breaking packages installed in other environments.

  • What can a virtual environment contain:

    • A specific Python interpreter and software libraries needed to support a project.

    These project-specific software are stored in a directory, conventionally named venv or .venv inside the project directory.

Creating and Activating a Virtual Environment in Python using venv

  • Command to create a new virtual environment:

        mkdir  myProj             // Make directory for project "myProj"
        cd     myProj
    
        python -m venv myvenv     // Create virtual env "myvenv" 

  • The utilities for activating and deactivating the virtual environment --- as well as the local copy of Python interpreter are placed in the bin folder (in Linux):

    ls myvenv/bin
    
    Activate.ps1  activate.csh   pip*   pip3.9*  python3@
    activate      activate.fish  pip3*  python@  python3.9@
    

  • To activate the virtual environment, run:

      source  myvenv/bin/activate
    

Checking If Python is Running Inside a Virtual Environment

  • Start the Python interpreter:

      >> python
    

  • Import the sys module and print the sys.path variable:

    >>> import sys
    >>> sys.path
    
    You will see this path in the output:
    
     '/home/cheung/python/02-env/myProj/myvenv/lib/python3.9/site-packages'