A virtual environment is a sandbox for packages. Pip's default behavior is system level. However, packages installed in different virtual environment do not co-mingle. The ideal is for each project to have its own distinct virtual environment.
This is especially important on team projects. The virtual environment provides a means to a standard for packages. Identifying project dependencies and which package versions have already been tested against the code.
It is common to see virtual environments named after the project it represents. The virtual enviromment in this sample will be called venv
.
From a command shell. Set the Working Directory to the project's.
python
can be used to create a new virtual environment by pasing the -m
parameter
python -m venv venv
Once present, another step is necessary to activate the virtual environment.
Activate the virtual environment on Mac or Linux.
source ./venv/bin/activate
For Windows
./venv/bin/activate
It's not safe to install new packages, or run your Python script,
Troubleshooting Tips
-
Ensure python is in your path with
which python
-
Mac users with Xcode, try
python3
andpip3
.
To save your virtual environment's pips; Create a requirements.txt. pip
can create a requirements.txt by redirecting the output from pip freeze
to requirements.txt
pip freeze > requirements.txt
If the project uses source control, it is best not to add the venv
directory. Including the requirements.txt is adequate.
git add requirements.txt
When joining a project already in progress. After git clone
finishes. Check if there is a requirements.txt in the project's source code, pip can be used to regenerate the venv
directory. To do this use pip install
with the -r
pip install -r requirements.txt
All of the requirements will be downloaded and a new virtual environment will be created for you.