This article uses the Python 3 included venv module. Make sure Python 3.3 or later is installed on your computer. To check, open a terminal and enter:
python3 --version
Open the terminal and enter:
mkdir project1
cd project1
python3 -m venv env
A folder env
has been created in project1
. This folder contains all packages you will install for this project. To install packages, you first need to activate the virtual environment.
source env/bin/activate
Notice that the terminal prompt now starts with (env)
.
As long as the virtual environment is activated, all pip
commands apply to that environment. To check what packages are installed, enter the following command:
pip list
Python might notify you with You are using pip version xx.x.x, however version yy.y.y is available.
You should consider upgrading via the 'pip install --upgrade pip' command
. If it does, do as it tells you and enter:
pip install --upgrade pip
For this example, you will install Reactive extensions for python. To install packages, check if your prompt starts with (env)
and enter the usual pip command like this:
pip install rx
Uninstall packages with the usual pip command like this:
pip uninstall rx
Type pip list
any time you like to see what is in the virtual environment.
If you have closed the terminal and want to continue working on project1, open a terminal and enter:
cd project1
source env/bin/activate
The env
folder grows as you are installing packages. If you are planning to add the project to version control, you probably don’t want to commit the packages-source-code. Instead you want to add a list with dependencies (packages) so the project can be co-developed other machines. To make that list, open a terminal and enter:
pip freeze > requirements.txt
The contents of requirements.txt
looks like this:
Rx==1.6.1
That list grows when you install more packages. requirements.txt
can be committed to source control.
After cloning a project to a new machine, the dependencies need to be installed in the projects virtual environment. To do this for project1, open a terminal and enter:
cd project1
python3 -m venv env
source env/bin/activate
pip install -r requirements.txt
And that’s it! You have now learned how to use a virtual environment in Python3 with the following advantages: