A Python virtual environment is a self-contained directory that contains its own installation of Python and other related packages. It allows you to create isolated Python environments, each with its own set of dependencies, without affecting the system Python installation or other virtual environments. This is particularly useful when you need to work on multiple Python projects with different requirements or versions of packages.
To create a virtual environment, you can use the venv
module that comes with Python. The basic steps involve creating a new project directory for the virtual environment, activating it, and then installing any necessary packages using pip.
Here's an example of how to activate python virtual environment in project folder called pythonArduino:
PS D:\visualstudiocode\pythonArduino> python -m venv pythonArduino
PS D:\visualstudiocode\pythonArduino> pythonArduino/Scripts/activate
(pythonArduino) PS D:\visualstudiocode\pythonArduino>
This will create a new virtual environment in the pythonArduino
directory and activate it.
See the following video:
Then we can proceed to install any python libraries using
pip install
followed by package_name
. The libraries or package you install will only be available within this virtual environment. For example to install pyserial library we use the following command:> pip install pyserial
When you're done working on the project, you can deactivate the virtual environment using the deactivate
command:
> deactivate