Beyond the Standard Library
Chapter 2: Virtual Environments
Venv
Python’s solution for managing package installations is via Venv. The idea is that you create a self-contained environment for each project you have.
For example, you can have an environment called finalproject
for your amazing individual project, webapp
for your revolutionary web application development code, etc. Each environment will have its own package installations, so the installations do not interfere with one another.
In practice, if you have a git repository containing the code for your project, then you might want to have an environment solely for running code in this repo. Most people just name the environment env
or venv
.
Of course, your main Python installation can still have the main packages that you use frequently, especially if the package versions are not critical for your general use. Having a virtual environment can save you from having to install packages that might only be used for one specific project.
Creating your virtual environment
Let’s say you need to create a virtual environment for your project. Say you want to name it my_env
. Go to your project directory, and do the following (use python3
/python3.8
as appropriate):
user@MACHINE:~/ai_project$ python3 -m venv my_env
You should now see a directory called my_env
in your project directory. This is where Python will install the packages for your environment.
If you are using git, you should exclude this virtual environment directory from your repo using .gitignore
. There is no point committing all these files or worse pushing them to a remote repo (you should not usually push executables to git repos). It is easier to just recreate the virtual environment (we will discuss that shortly)!