Introduction π
A Virtual Environment (venv) is an isolated Python workspace where you can install packages without affecting your global Python installation or other projects. This is essential for clean, conflict-free development.
Note
1. Why Use a Virtual Environment? π€
- β Keep project dependencies separate
- β Avoid global installation conflicts
- β Use different package versions for different projects
- β Cleaner and safer development workflow
2. Creating a Virtual Environment π§±
Windows
create_venv_windows.cmd
python -m venv envMac / Linux
create_venv_unix.sh
python3 -m venv envβ This creates a folder named env/ containing the isolated environment.
3. Activating the Virtual Environment βΆοΈ
Windows
activate_windows.cmd
env\Scripts\activateMac / Linux
activate_unix.sh
source env/bin/activateNote
4. Installing Packages Inside the Virtual Environment π¦
pip_install.py
pip install requests
pip install numpyβ Packages install ONLY inside the environment, not globally.
5. Checking Installed Packages π
pip_list.py
pip listpip_freeze.py
pip freezeβ pip freeze is useful for exporting dependencies.
6. Deactivating the Environment β
deactivate.sh
deactivateNote
7. Requirements File (For Sharing Environments) π
Export installed packages
requirements_export.sh
pip freeze > requirements.txtInstall from requirements.txt
requirements_install.sh
pip install -r requirements.txtβ Perfect for sharing projects or deploying to servers.
8. Using Multiple Virtual Environments π§
multiple_envs.sh
projectA/env/
projectB/env/
projectC/env/β Each project gets its own isolated environment.
9. Virtual Environment Folder Structure π
venv_structure
env/
bin/ or Scripts/
lib/
include/
pyvenv.cfg| Folder/File | Purpose |
|---|---|
| bin / Scripts | Executables including Python & pip |
| lib | Installed packages |
| pyvenv.cfg | Configuration of the virtual environment |
10. Using Virtual Environment in VS Code π»
1οΈβ£ Open project folder in VS Code
2οΈβ£ Press Ctrl + Shift + P β βPython: Select Interpreterβ
3οΈβ£ Choose the interpreter inside env/bin or env/Scripts
Note
11. Virtualenv vs venv π
| venv | virtualenv |
|---|---|
| Built-in (Python 3.3+) | External package |
| Basic features | More advanced controls |
| Slower creation | Faster & feature-rich |
12. Real-World Example π
realworld_workflow.sh
mkdir myproject
cd myproject
python -m venv env
source env/bin/activate
pip install flask
pip freeze > requirements.txtβ Your Flask project now has a fully isolated setup.
Conclusion π
You now fully understand Virtual Environments in Python! Want the next topic? Try File Handling, Import System, OOP (Classes & Objects), or Exception Handling. Just tell me! π