Creating a Python virtual environment
When you write Python applications, you will usually use packages and modules that are not included in the standard Python library. You may have Python applications that require a different version of the same module. However, only a specific version of a module can be installed system-wide. If you upgrade a module version for an application, you might end up breaking other applications that require an older version of that module.
To address this issue, you can use Python virtual environments. With virtual environments, you can install Python modules in an isolated location rather than installing them system-wide. Each virtual environment has its own Python binary and can have its own independent set of installed Python packages in its site-packages directory.
Since version 3.3, Python comes with the venv
library, which provides support for creating lightweight virtual environments. By using the Python venv
module to create isolated Python environments, you can use different package versions for different projects. Another advantage of using venv
is that you won’t need any administrative privileges to install Python packages.
If you are using Linux or macOS, create an isolated environment with the following command:
python -m venv my_env
Remember to use python3
instead of python
if your system comes with Python 2 and you installed Python 3.
If you are using Windows, use the following command instead:
py -m venv my_env
This will use the Python launcher in Windows.
The previous command will create a Python environment in a new directory named my_env
. Any Python libraries you install while your virtual environment is active will go into the my_env/lib/python3.12/site-packages
directory.
If you are using Linux or macOS, run the following command to activate your virtual environment:
source my_env/bin/activate
If you are using Windows, use the following command instead:
.\my_env\Scripts\activate
The shell prompt will include the name of the active virtual environment enclosed in parentheses, like this:
(my_env) zenx@pc:~ zenx$
You can deactivate your environment at any time with the deactivate
command. You can find more information about venv
at https://docs.python.org/3/library/venv.html.