Introduction to Virtual Environments 1
-
What Is It?
A virtual environment is simply an isolated environment for Python projects.
-
Why Use Virtual Environments?
- Provide isolation between system site directories.
- Each project can have its own set of dependencies.
-
Virtual Environments With Anaconda
anaconda
Creating A Virtual Environment
Let’s create a virtual environment called “aws”.
We will specify that this virtual environment should use Python version 3.7.
(base) rd$ conda create -n aws python=3.7
(base) rd$
-
Activating Virtual Environment
(base) rd$ conda activate aws
(aws) rd$
-
Installing Packages
Installing packages from Anaconda
(aws) rd$ conda install boto3
If a package is not available from conda or Anaconda.org, you may be able to find and install the package via conda-forge or with another package manager like pip.
(aws) rd$ pip install boto3
-
Create Requirements File
(aws) rd$ conda list -e > requirements.txt
-
Listing Virtual Environments
(aws) rd$ conda env list
# conda environments:
#
base /Users/rd/opt/anaconda3
aws * /Users/rd/opt/anaconda3/envs/aws
(aws) rd$
-
Removing Virtual Environments
(aws) rd$ conda activate base
(base) rd$ conda remove --name aws --all
Remove all packages in environment /Users/rd/opt/anaconda3/envs/aws:
## Package Plan ##
environment location: /Users/rd/opt/anaconda3/envs/aws
The following packages will be REMOVED:
ca-certificates-2020.1.1-0
certifi-2019.11.28-py37_0
...
Proceed ([y]/n)? y
Preparing transaction: done
Verifying transaction: done
Executing transaction: done
(base) rd$
-
Create Virtual Environment
Using Requirements File
(aws) rd$ conda create --name=aws --file=requirements.txt
-
Virtual Environments With Pipenv
-
Virtual Environments With venv
The One True Way
-
Create a VENV (Virtual ENVironment)
This is the One True Way…
python3 -m venv ./venv
-
Activate the venv
AND you have to activate the venv everytime you start working on the project in a shell.
cd _to your project_
source ./venv/bin/activate
# and you should see (venv) in your prompt...
-
Seeing what installed and freezing it.
To see what is in the venv
python3 -m pip freeze
# and then
python -m pip freeze > requirements.txt
-
And loading those dependencies for the venv
python -m pip -r requirements.txt
Wow. This way your repo doesn’t have all the code from all these packages.
-
And Make Sure
Make sure your .gitignore file has a line…
venv/
(Don’t put your venv up in your repo either!).
-
The End
