Virtual environments
by Antoine - categories : Programming Python
Virtual environment (aka. virtualenv or venv) is a very convenient tool, allowing to set partitioned environment for packages setup. It's very handy especially for developers - but not only - when it comes to install packages used, for instance, as a specific app libraries.
This way, one can add to its common (default, system-wide) environment multiples virtual envs he can switch on/off to access the specific packages. It's also a simple way to manage different versions of the same library for different projects, and to store and port all their dependencies inside the projects directories.
Common use
Let's say you're developing an app which uses a 3rd tier crypto library. You don't want/need this library to be accessible system-wide at anytime. More
Setup
Prefered setup on Linux will be with the default package manager (APT, YUM...).
a@ae:~$ apt install virtualenv
Or on any OS with PIP (package installer for Python).
a@ae:~$ pip3 install virtualenv
Create a new virtual venv
a@ae:~/Git$ virtualenv ./MyProject/venv
created virtual environment CPython3.9.2.final.0-64 in 192ms
[...]
This only creates a new folder (venv) inside the project folder. The venv is not activated yet.
Activate and deactivate a venv
Activate
a@ae:~/Git/MyProject$ source venv/bin/activate
(venv) a@ae:~/Git/MyProject$
The (venv) tag on the prompt shows that the virtual environment is activated and any command typed will be executed in its context. A newly created venv comes with (default) minimal packages setup, compared to the global environment.
a@ae:~/Git/MyProject$ pip list
Package Version
-------------- -------
distlib 0.3.6
filelock 3.8.0
pip 20.3.4
pip-autoremove 0.10.0
platformdirs 2.5.2
setuptools 52.0.0
virtualenv 20.16.5
wheel 0.34.2
a@ae:~/Git/MyProject$ source venv/bin/activate
(venv) a@ae:~/Git/MyProject$pip list
Package Version
---------- -------
pip 22.2.2
setuptools 65.3.0
wheel 0.37.1
Any package and dependencies installed while the venv is activated will be in the venv only.
(venv) a@ae:~/Git/MyProject$ pip3 install PyNaCl
Collecting PyNaCl
Downloading PyNaCl-1.5.0-cp36-abi3-manylinux_2_17_x86_64.manylinux2014_x86_64.manylinux_2_24_x86_64.whl (856 kB)
━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━ 856.7/856.7 kB 4.0 MB/s eta 0:00:00
[...]
(venv) a@ae:~/Git/MyProject$ pip list
Package Version
---------- -------
cffi 1.15.1
pip 22.2.2
pycparser 2.21
PyNaCl 1.5.0
setuptools 65.3.0
wheel 0.37.1
Deactivate
This time, we use the system-wide command deactivate
to release the user from any active virtual env.
(venv) a@ae:~/Git/MyProject$ deactivate
a@ae:~/Git/MyProject$
Be the first to comment 🡮