Lesson 1.3: Set Up Python Virtual Environment
Due to the nature of open source for many python libraries, some libraries upgrades may break some other libraries that depend on them. In order to get around this, we occasionally need to use a specific version of a library instead of the latest version.
As a best practice, we can create a virtual environment for each project. A virtual environment is a self-contained directory that contains a Python installation for a particular version of Python, plus a number of additional packages.
To create a virtual environment, run the following command:
cd ~
python -m venv myvenv
This command creates a directory called myvenv
that contains a Python installation and a number of additional packages. To activate the virtual environment, run the following commands:
In bash (for mac and linux):
source ~/myvenv/bin/activate
To make it more convenient, you can add the following line to your .bashrc
or .bash_profile
:
alias myvenv="source ~/myvenv/bin/activate.sh"
Then you can activate the virtual environment by running the following command in Windows PowerShell:
.\C:\Users\$env:USERNAME\myvenv\Scripts\Activate.ps1
To make it more convenient, you can add the following line to your PowerShell profile:
Set-Alias -Name myvenv -Value ".\C:\Users\$env:USERNAME\myvenv\Scripts\Activate.ps1"
Then you can activate the virtual environment by running:
myvenv