Skip to content

Latest commit

Β 

History

History
113 lines (79 loc) Β· 2.31 KB

File metadata and controls

113 lines (79 loc) Β· 2.31 KB

Python Virtual Environments

How to create and use virtual environments in Python.

πŸ“ Cheatsheet: How to Create a Project with Separate venv


πŸ“¦ When to Use

  • Each separate project should have its own virtual environment (venv).
  • To keep project libraries isolated.
  • To make projects portable and easy to maintain.

πŸ› οΈ Steps for Every New Project

  1. Go to your main repository folder (e.g., coding_school/):

    cd ~/projects/coding_school
  2. Create a folder for the new project:

    mkdir project_name
    cd project_name
  3. Create a virtual environment inside this folder:

    python3 -m venv venv

    πŸ”Ή Why venv twice?

    • First venv = Python module to create virtual environments.
    • Second venv = The folder name for your environment (you can name it anything, but venv is common).
  4. Activate the virtual environment:

    source venv/bin/activate
  5. Install necessary libraries:

    pip install requests
    pip install Pillow
  6. Save installed libraries into requirements.txt:

    pip freeze > requirements.txt
  7. Create your main code file:

    touch main.py
  8. Check your .gitignore at repository root:
    Add this line:

    */venv/

    To make sure Git does not track your venv folders.


πŸ“ Example Project Structure

coding_school/
β”œβ”€β”€ .gitignore
β”œβ”€β”€ project1/
β”‚   β”œβ”€β”€ venv/
β”‚   β”œβ”€β”€ main.py
β”‚   β”œβ”€β”€ requirements.txt
β”‚   └── README.md
β”œβ”€β”€ project2/
β”‚   β”œβ”€β”€ venv/
β”‚   β”œβ”€β”€ main.py
β”‚   β”œβ”€β”€ requirements.txt
β”‚   └── README.md

🧠 Quick Reference Table

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

✨ SUMMARY

One project β†’ One folder β†’ One venv β†’ One requirements.txt

Stay organized and professional!