Virtual Environments
With Python being very common now, different libraries and versions can be required by different programs. Different operating systems have dealt with this kind of issue in different ways in the past,usually by trying to share libraries across the whole system[^4] but with modern development the goal is portability and ease of development rather than raw efficiency. Python programmers have the option of using Virtual Environments for their software projects, in which the libraries are installed specifically for their software, with exactly the right versions, and even the python interpreter is fixed and separate from the system-wide interface.
Below is the quick-start guide to using virtual environments. Detailed information is available here: https://docs.python.org/3/tutorial/venv.html
The quick-start expects a Linux environment, but this can also be used on Windows with slight changes.
Creating a Virtual Environment
The environment is all contained within a directory. So if your
project is in ~/myCodez
and we create a virtual environment called
venv
, then it will probably be best placed in ~/myCodez/venv
.
From the ~/myCodez
directory, use python3 -m venv venv
. In the
example below, you can see the result.
Inside that directory are now a complete set of files for a separate python environment.
Activating a Virtual Environment
While in your source directory, type . ./venv/bin/activate
(note the
leading dot) to activate it. This changes your environment variables
so if you install modules, they go in your virtual environment, when
you run python
, it is running from the version in the virtual
environment, etc.
You can verify this using which
1.
As you can see from the screenshot, if you're using the provided VM
then the default shell is zsh
and it is configured to show
information about whether you're in an activated virtual environment2.
Check Your Understanding
Make sure you can recreate the example above, in which a virtual environment is created and activated.