Python Virtual Environment Basic Commands

Posted by Ray on October 14, 2020

This document is a straightforward guide for python virtualenvironment basic commands.

Virtual Environments

Create a virtual environment

  1. Change directory into desired folder where venv will be placed.

    1
    
     $ cd ../my_directory
    
  2. Create a virtual environment.

    1
    2
    
     python[version] -m venv <venv_name>
     $ python3 -m venv venv
    
  3. Activate the virtual environment created.

    1
    2
    
     $ cd venv
     $ source bin/activate
    

Delete all packages installed by pip inside the virtual environment

  1. Activate your virtual environment.

    1
    2
    
     $ cd ../venv
     $ source bin/activate
    
  2. Delete all packages.

    1
    
     $ pip uninstall -y -r <(pip freeze)
    
  3. Deactivae the virtual environment.

    1
    
     $ deactivate
    

Installing packages inside virtual environment

  1. Activate your virtual environment.

    1
    2
    
     $ cd ../venv
     $ source bin/activate
    
  2. Install desired package.

    • Installing individual packages
      1
      
        $ pip install my_package
      
    • Installing requirements.txt
      1
      
        $ pip install -r requirements.txt
      

Determine if you are inside a virtual environment

  1. Activate your virtual environment.

    1
    2
    
     $ cd ../venv
     $ source bin/activate
    
  2. Run python.

    1
    
     $ python3
    
  3. Import os and get virtual env from os.

    1
    2
    
     $ >>> import os
     $ >>> os.getenv('VIRTUAL_ENV')
    
    • If the terminal displays a path, you are inside a virtual env.
    • If the terminal displays nothing, you are not inside a virtual env.