Appearance
venv
When developing Python applications, the system typically has only one version of Python 3 (3.x). All third-party packages installed via pip go into the Python 3 site-packages directory.
The Need for Isolation
If you're developing multiple applications, they will share the same Python environment. For example, if Application A needs Jinja 2.7 and Application B requires Jinja 2.6, conflicts arise.
To solve this, each application can have its own "isolated" Python runtime environment using venv.
Creating a Virtual Environment
Let’s assume you're starting a new project named project101 and need a dedicated Python environment:
Create a Directory: First, create a directory for your virtual environment. Here, we'll name it
proj101env:bash$ mkdir proj101env $ cd proj101env/Set Up the Virtual Environment: Create an isolated Python environment:
bashproj101env$ python3 -m venv .After running this command, you will see several folders and a
pyvenv.cfgfile:bashproj101env$ ls bin include lib pyvenv.cfgThe command
python3 -m venv <directory>sets up an independent Python environment. Thebindirectory contains executable files likepython3andpip3, which are symlinks to the system Python installation.Activate the Virtual Environment: Change into the
bindirectory and activate the environment. On Linux/Mac, use:bashproj101env$ cd bin bin$ source activateOn Windows, use:
bashproj101env$ activate.batYour command prompt will change to indicate that the
proj101envenvironment is active:bash(proj101env) bin$Install Packages: Now you can install packages without affecting the system Python environment:
bash(proj101env) bin$ pip3 install jinja2You can verify the installation:
bash(proj101env) bin$ python3 >>> import jinja2 >>> exit()Packages installed in the
venvenvironment go intoproj101env/lib/python3.x/site-packages, keeping the system environment untouched.Deactivate the Environment: To exit the virtual environment, simply run:
bash(proj101env) bin$ deactivateYou'll return to the normal system environment, where
pipandpythonpoint to the system installation.
Deleting a Virtual Environment
If you no longer need a particular venv, such as proj101env, you can easily delete it. Ensure it's not activated, then remove the directory:
bash
$ rm -rf proj101envSummary
venv provides isolated Python environments for applications, helping to avoid conflicts between different versions of packages required by various applications. This isolation allows for better management of dependencies across projects.