Virtual Environments in Python

Loading

A virtual environment in Python is an isolated workspace that allows you to manage dependencies for a specific project without affecting system-wide or other project dependencies. It ensures that each project has the required libraries and package versions, avoiding conflicts.


1. Why Use Virtual Environments?

Avoid Dependency Conflicts – Different projects can use different versions of the same package.
Keep System Python Clean – Prevent unnecessary installations in the global environment.
Easier Deployment – Ensure projects run with the correct dependencies.
Reproducibility – Share the exact dependencies with others using requirements.txt.


2. Creating a Virtual Environment

Python provides the built-in venv module to create virtual environments.

2.1 Create a Virtual Environment

python -m venv myenv

This creates a folder myenv/ with a local Python environment.


3. Activating a Virtual Environment

You need to activate the virtual environment before installing packages.

3.1 On Windows (Command Prompt)

myenv\Scripts\activate

You should see (myenv) appear before the command prompt.

3.2 On Windows (PowerShell)

myenv\Scripts\Activate.ps1

3.3 On macOS/Linux

source myenv/bin/activate

4. Installing Packages in a Virtual Environment

Once activated, you can install packages using pip.

pip install requests numpy

Packages are installed inside myenv/, not system-wide.

4.1 Check Installed Packages

pip list

4.2 Freeze Dependencies

To save installed packages for sharing or deployment:

pip freeze > requirements.txt

This creates a requirements.txt file listing all installed packages.

4.3 Install Dependencies from requirements.txt

To recreate the environment on another system:

pip install -r requirements.txt

5. Deactivating a Virtual Environment

To exit the virtual environment:

deactivate

This returns you to the system Python environment.


6. Deleting a Virtual Environment

Simply delete the myenv/ folder:

rm -rf myenv  # macOS/Linux
rmdir /s myenv # Windows

7. Using virtualenv Instead of venv

virtualenv is an older alternative to venv with more features. Install it with:

pip install virtualenv

Create an environment:

virtualenv myenv

8. Using pyenv for Multiple Python Versions

If you need different Python versions for different projects, use pyenv:

pyenv install 3.9.12
pyenv virtualenv 3.9.12 myenv
pyenv activate myenv

9. Summary

CommandDescription
python -m venv myenvCreate a virtual environment
myenv\Scripts\activateActivate (Windows)
source myenv/bin/activateActivate (macOS/Linux)
pip install package_nameInstall a package
pip freeze > requirements.txtSave dependencies
pip install -r requirements.txtInstall dependencies
deactivateExit the environment
rm -rf myenvDelete the environment

Leave a Reply

Your email address will not be published. Required fields are marked *