Python Virtual Environment Setup


What is a Python Virtual Environment?

A Python virtual environment (venv) is an isolated environment where you can install specific packages without affecting the global Python setup. This is crucial for working on multiple projects with different dependencies.




Benefits of Using a Virtual Environment

  • Avoids package conflicts
  • Keeps projects isolated
  • Makes deployment easier
  • Ideal for collaboration and testing


How to Create a Virtual Environment in Python


Step 1: Install Python (if not already)

Make sure Python 3 is installed:

python --version

or

python3 --version

Step 2: Install venv (comes pre-installed with Python 3.3+)

For Linux (if not available):

sudo apt install python3-venv

Step 3: Create a Virtual Environment

python -m venv env

Or:

python3 -m venv env

Here, env is the name of the virtual environment folder.


Step 4: Activate the Virtual Environment

On Windows:

env\Scripts\activate

On macOS/Linux:

source env/bin/activate


Once Activated

You'll see your terminal prefixed like this:

(env) your-computer:~/your-project$

Now you can install packages using pip:

pip install requests

Packages will be installed only inside the env folder, not globally.


Deactivating the Virtual Environment

To exit the environment:

deactivate



Project Folder Structure Example

my_project/
│
├── env/               ← virtual environment
├── app.py
├── requirements.txt

Save Installed Packages

You can freeze the dependencies to a requirements.txt file:

pip freeze > requirements.txt

To install them later:

pip install -r requirements.txt


Pro Tips

  • Always use a virtual environment per project
  • Use .gitignore to exclude env/ from version control
  • Use requirements.txt for deployment and reproducibility