How to create and use virtual environments in Python.
- Each separate project should have its own virtual environment (
venv). - To keep project libraries isolated.
- To make projects portable and easy to maintain.
-
Go to your main repository folder (e.g.,
coding_school/):cd ~/projects/coding_school
-
Create a folder for the new project:
mkdir project_name cd project_name -
Create a virtual environment inside this folder:
python3 -m venv venv
πΉ Why
venvtwice?- First
venv= Python module to create virtual environments. - Second
venv= The folder name for your environment (you can name it anything, butvenvis common).
- First
-
Activate the virtual environment:
source venv/bin/activate -
Install necessary libraries:
pip install requests pip install Pillow
-
Save installed libraries into
requirements.txt:pip freeze > requirements.txt -
Create your main code file:
touch main.py
-
Check your
.gitignoreat repository root:
Add this line:*/venv/To make sure Git does not track your
venvfolders.
coding_school/
βββ .gitignore
βββ project1/
β βββ venv/
β βββ main.py
β βββ requirements.txt
β βββ README.md
βββ project2/
β βββ venv/
β βββ main.py
β βββ requirements.txt
β βββ README.md
| Action | Command |
|---|---|
| Create a new project | mkdir project_name |
| Create a new venv | python3 -m venv venv |
| Activate the venv | source venv/bin/activate |
| Install libraries | pip install ... |
| Save dependencies | pip freeze > requirements.txt |
| Protect venv in Git | Add */venv/ to .gitignore |
One project β One folder β One venv β One requirements.txt
Stay organized and professional!