Python Virtual Environment

🐍 Python Virtual Environment

A virtual environment (venv) in Python is an isolated workspace where you can install packages specific to a project without affecting the global Python installation or other projects.


✅ Why Use a Virtual Environment?

Without venvWith venv
Packages install globallyPackages isolated per project
Version conflicts may occurEach project can have different versions
Hard to manage dependenciesEasy and clean dependency management

🛠 Create a Virtual Environment

Step 1: Check Python version

python --version

or (on some systems)

python3 --version

Step 2: Create a virtual environment

python -m venv myenv

Here, myenv is the environment name — you can rename it.


▶ Activate the Virtual Environment

OSCommand
Windows (CMD)myenv\Scripts\activate
Windows (PowerShell).\myenv\Scripts\Activate.ps1
Mac / Linuxsource myenv/bin/activate

🎉 After Activation

You will see something like:

(myenv) C:\Users\User\project>

Now, anything you install will go inside myenv.


📦 Installing Packages

pip install flask

📃 Freeze Installed Packages

To save installed dependencies (useful for sharing projects):

pip freeze > requirements.txt

📥 Install Packages from requirements.txt

pip install -r requirements.txt

⛔ Deactivate the Virtual Environment

deactivate

🧹 Remove a Virtual Environment (Optional)

Just delete the folder:

myenv

Quick Workflow Summary

cd project-folder
python -m venv myenv
myenv\Scripts\activate (or source myenv/bin/activate)
pip install package_name
pip freeze > requirements.txt
deactivate

You may also like...