Python Classroom Series – 29/Jul/2021

Virtual Environments in Python

  • The main purpose of virtual environments is to create an isolate environment for python projects which means each project can have its own dependencies, regardless of the every other project
  • To get started with virtual environments
pip install virtualenv
  • If you are uisng python3 you should already have venv module
  • Create a new directory
mkdir projecta
cd projecta
  • Create a virtual environment
python -m venv venv

Preview

  • To activate virtualenvironment from command line
# windows
venv\Scripts\Activate.ps1
# mac or linux
venv/bin/activate

Preview

  • Create two folders
    • projecta
    • projectb
  • Create a virtual environment for projecta
  • Activate virtual environment for project a and execute
pip install flask
  • Observe the sitepackages folder in venv
  • Execute the following command
pip freeze

Preview

  • Create a Virtual environment for projectb
  • Activate virtual environment for project b and execute
pip install django
  • Observe the sitepackages folder in venv
  • Execute the following command
pip freeze

Preview

  • Generally when we work on projects and install dependecies for our projects we want others who work on the same project to install exact dependencies
  • To make it visible and easy for others to install exact packages we create requirements.txt file which will have the packages with version number i.e. the output of freeze command
pip freeze > requirements.txt
  • so now lets take a open source python project ansible
  • To make this work in our local setup we first get the code
git clone https://github.com/ansible/ansible.git

Preview

Activating virtual environments with Visual Studio Code

  • Open the folder projecta/projectb with visual studio code
  • In windows Enter (Ctrl+Shift+p) and select Python: Select Interpreter Preview Preview Preview

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

About learningthoughtsadmin