93. Virtual Environments with virtualenv

Here are 10 Python snippets and examples to demonstrate the use of virtualenv for managing project dependencies and isolated environments:


1. Creating a Virtual Environment

# Install virtualenv if not already installed
pip install virtualenv

# Create a new virtual environment named "env"
virtualenv env

Creates a virtual environment named env in the current directory.


2. Activating a Virtual Environment

# On macOS/Linux
source env/bin/activate

# On Windows
env\Scripts\activate

Activates the virtual environment so all installed packages are isolated to it.


3. Checking Installed Packages in the Virtual Environment

# After activating the environment
pip list

Displays the list of installed packages within the activated virtual environment.


4. Installing Packages in the Virtual Environment

Installs a package, which is isolated to the virtual environment.


5. Deactivating the Virtual Environment

Returns to the global Python environment by deactivating the virtual environment.


6. Specifying Python Version for Virtual Environment

Specifies a Python version to use in the virtual environment.


7. Freezing Dependencies

Creates a requirements.txt file listing all installed dependencies.


8. Installing Dependencies from a File

Installs dependencies in bulk from a requirements.txt file.


9. Using Virtualenvwrapper for Better Management

Enhances virtualenv with features like global environment storage and named environment switching.


10. Deleting a Virtual Environment

Deletes the env directory to completely remove the virtual environment.


Why Use virtualenv?

  • Isolation: Keeps dependencies for each project separate.

  • Reproducibility: Ensures consistent environments across machines.

  • Python Version Control: Easily create environments with specific Python versions.

  • Dependency Management: Simplifies dependency installation and freezing.

These examples provide the essential commands and workflows for using virtualenv effectively in Python projects.

Last updated