Python Virtual Environments
A virtual environment is a private folder with its own Python and packages. Each project can have its own virtual environment.
Create the folder
This command builds a new environment. The new folder here is called myenv.
python3 -m venv myenvActivate on Mac and Linux
Activation points your terminal at the private toolbox. You run it once per terminal session.
source myenv/bin/activateActivate on Windows
Windows uses a different path for the same job. The idea is exactly the same.
myenv\Scripts\activateSave the package list
Freeze writes the exact package list to a file. A teammate can rebuild the toolbox from that file.
pip freeze > requirements.txtLeave when you finish
One short command leaves the environment. Your terminal goes back to the normal Python.
deactivateExample
python3 -m venv myenv
source myenv/bin/activate
pip install requests
pip freeze > requirements.txt
deactivateKey points
- Virtual environment: a private folder with its own Python and packages
- Use python3 -m venv to create one for a project
- Use the activate command for your system to start using it
- The terminal prompt shows the environment name while it is active
- Use pip freeze > requirements.txt to save your package list
- Use deactivate to leave the environment
In this example, you read a terminal transcript. It is not a program to run. The first command creates the myenv folder. The second command activates it, and the prompt gains the name (myenv). The install then adds requests inside myenv only, and the output line confirms it. Freeze saves the package list to requirements.txt. Deactivate leaves the environment at the end.
Note
On Windows, you run python, not python3, in most setups.
The rest of the steps work the same way.
Try it Yourself
Edit the code, then press Run.
Running is simulated · Python Playground
Exercise
Why does each project get its own virtual environment?