# 93. Virtual Environments with virtualenv

**1. Creating a Virtual Environment**

```bash
# 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**

```bash
# 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**

```bash
# After activating the environment
pip list
```

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

***

**4. Installing Packages in the Virtual Environment**

```bash
# Install Flask within the virtual environment
pip install flask

# Check the installed version of Flask
pip show flask
```

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

***

**5. Deactivating the Virtual Environment**

```bash
# Deactivate the virtual environment
deactivate
```

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

***

**6. Specifying Python Version for Virtual Environment**

```bash
# Create a virtual environment using a specific Python version
virtualenv -p python3.9 env
```

Specifies a Python version to use in the virtual environment.

***

**7. Freezing Dependencies**

```bash
# Generate a requirements.txt file with all installed packages
pip freeze > requirements.txt
```

Creates a `requirements.txt` file listing all installed dependencies.

***

**8. Installing Dependencies from a File**

```bash
# Install packages listed in requirements.txt
pip install -r requirements.txt
```

Installs dependencies in bulk from a `requirements.txt` file.

***

**9. Using Virtualenvwrapper for Better Management**

```bash
# Install virtualenvwrapper
pip install virtualenvwrapper

# Export environment variable (Add to .bashrc/.zshrc)
export WORKON_HOME=~/Envs

# Create a virtual environment
mkvirtualenv myenv

# Activate a virtual environment
workon myenv

# Deactivate the virtual environment
deactivate
```

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

***

**10. Deleting a Virtual Environment**

```bash
# Remove the virtual environment directory
rm -rf env
```

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.
