A virtual environment is necessary when a user tries to install a package using Python's own pip package manager. Many Linux distros tend to block this type of installation because it will create a clash with their own package manager. Because of that, the best way to use Python Package Manager is to create a virtual environment and install the required Python packages there. There are several ways to create a virtual environment in Python, but in this article, I will show the recommended way to create a virtual environment in Python.
First, visit the directory where you would like to create this virtual environment. Most of the time, it will be the project folder.
python3 -m venv <venv name>
To activate this environment write the following command.
source <venv name>/bin/activate
After typing the command, you will notice the virtual environment name on the left side of the terminal screen. Like this
Here, the name of the virtual environment is nsvenv. After that, install as many packages as you need for the project. To use this environment in VS Code, just look at the bottom bar, where you will see it has already selected a venv that you have created for this project.
If it is not selected and showing only Python, then click the icon, and you will see a drop-down box like this.
Find the virtual environment that you have created and select it.
After setting up everything properly, an error can be noticed while downloading the package from the pip. You may encounter an error like "ERROR: Cannot perform a '--user' install. User site packages are not visible in this virtual environment." To fix this issue, do the following steps:
Go to the
pyvenv.cfg
file in the virtual environment folder.Set
include-system-site-packages
totrue
and save the change.Reactivate the virtual environment.
To deactivate a Python virtual environment, just type
deactivate
in the command line.
Photo Credit: ActiveState