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 venv With venv
Packages install globally Packages isolated per project
Version conflicts may occur Each project can have different versions
Hard to manage dependencies Easy 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

OS Command
Windows (CMD) myenv\Scripts\activate
Windows (PowerShell) .\myenv\Scripts\Activate.ps1
Mac / Linux source 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...