A virtual environment in Python is an isolated environment that allows you to install and manage packages independently from the global Python installation. This is particularly useful when working on multiple projects that require different dependencies or versions of packages.
Why Use a Virtual Environment?
- Avoid conflicts: Different projects might need different versions of the same package.
- Clean project setup: Keeps your project dependencies self-contained.
- Easier deployment: You can list all packages with
requirements.txtand replicate the environment elsewhere.
How to Use a Virtual Environment (Step-by-Step)
We will use the venv module, which is built into Python 3.3+.
Step 1: Create a Virtual Environment
python -m venv venvpython: Calls your Python interpreter.-m venv: Tells Python to run thevenvmodule.venv: The name of the directory that will contain the virtual environment.
This will create a folder named
venvwith all the necessary files to create an isolated environment.
Step 2: Activate the Virtual Environment
On Windows:
venv\Scripts\activateOn macOS/Linux:
source venv/bin/activateOnce activated, your shell prompt will change to something like:
(venv) your-username$Step 3: Install Packages in the Virtual Environment
Now you can install packages and they will be available only inside this environment.
pip install requestsYou can verify with:
pip listOnly packages in the virtual environment will be shown.
Step 4: Freeze the Environment
Create a requirements.txt file listing all installed packages:
pip freeze > requirements.txtStep 5: Deactivate the Environment
When you're done:
deactivateThis returns you to the global Python environment.
Example Project Structure
my_project/
?
??? venv/ ? Virtual environment files
??? main.py ? Your Python script
??? requirements.txt ? List of dependencies
Installing Environment from requirements.txt
If you're collaborating or deploying somewhere else:
python -m venv myenv
source myenv/bin/activate
pip install -r requirements.txt
