Setup a virtual environment for Python

The advantage of a virtual environment is when you install packages, it is separated from the system installation. Then, it allows you to keep your system Python installation clean. For each project, you can also have separate dependencies.


Linux

For Linux, you should check first if python3-virtualenv package is installed. If not:

 sudo apt-get install python3-virtualenv

Then, with the following command, the environment will be created (this is the same in Windows):

 python3 -m venv /home/pi/venv

First, you select the name that you want to give to your environment (venv) and then the folder when you want it to be stored. To activate it from “/home/pi” folder:

source venv/bin/activate

If you want to stop working on it:

deactivate

Windows

You can open PowerShell and navigate to the folder where you want to setup your virtualenv. dir command will show the content of your current folder, cd will help you navigate in it. Once in it, type:

python -m venv ./theNameOfYourVirtualEnv

To activate it in PowerShell, go to ./Scripts sub-folder and choose the Activate.ps1 file.