89. Virtual Environments with venv

The venv module in Python allows you to create isolated environments, which are crucial for managing project-specific dependencies without affecting the global Python environment. Below are 10 Python code snippets demonstrating the usage of venv for creating and managing virtual environments.

1. Creating a Virtual Environment

Copy

# Create a virtual environment named 'myenv'
python -m venv myenv

This command creates a new virtual environment in the myenv directory. It includes a fresh Python interpreter and libraries.


2. Activating a Virtual Environment on macOS/Linux

Copy

# Activate the virtual environment
source myenv/bin/activate

On macOS/Linux, you can activate the virtual environment using the source command.


3. Activating a Virtual Environment on Windows

Copy

# Activate the virtual environment on Windows
myenv\Scripts\activate

On Windows, the activation command is slightly different, using Scripts\activate.


4. Deactivating a Virtual Environment

Copy

To deactivate an active virtual environment, simply use the deactivate command. This will return to the global Python environment.


5. Installing Packages in a Virtual Environment

Copy

Once the virtual environment is activated, you can use pip to install packages specific to that environment.


6. Checking Installed Packages in a Virtual Environment

Copy

This will show all the packages installed in the virtual environment. It ensures that you are working with the correct dependencies for your project.


7. Creating a Virtual Environment with Specific Python Version

Copy

If you have multiple Python versions installed, you can specify which version to use when creating the virtual environment.


8. Freezing Dependencies into a Requirements File

Copy

This will create a requirements.txt file containing all the installed packages in your virtual environment, which can be shared for consistent setups.


9. Installing Dependencies from a Requirements File

Copy

To recreate the environment elsewhere or after cloning a project, you can install all dependencies from the requirements.txt file.


10. Verifying Python Version in Virtual Environment

Copy

Once the virtual environment is activated, you can verify the Python version being used in that environment, ensuring it matches the expected version.


Last updated