Create and activate a Python 3 virtual environment
Are you a python programmer that likes a clean computer? Would you like to organise your projects in a way they keep their dependencies close and don't affect global policy? After reading this article you know how to setup a virtual environment for each project. You'll learn how to install packages to it and how to create a list of dependencies for easy install on another machine.
Create a new Python project with virtual environment
Open the terminal and enter:
mkdir project1 cd project1 python3 -m venv env
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.
Activate virtual environment
Notice that the terminal prompt now starts with
Check what packages are installed for this project
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:
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
pip list any time you like to see what is in the virtual environment.
Come back to work on an existing project
If you have closed the terminal and want to continue working on project1, open a terminal and enter:
cd project1 source env/bin/activate
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:
That list grows when you install more packages.
requirements.txt can be committed to source control.
Install a project from source control on another machine
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:
- Keep packages (dependencies) in the project they belong to
- Prevent polluting your machine by installing stuff globally
- Allowing other developers to install all dependencies by running a single command