site logo

Learn to Python. Build the Future.


Category: (All)
❮  Go Back

14. How to Create and Use Python Virtual Environments with venv

Introduction

Managing project dependencies is crucial for Python development. The built-in venv module allows you to create isolated environments, ensuring that each project has its own set of dependencies, independent of others. This isolation prevents conflicts and simplifies dependency management.


1. What is a Virtual Environment?

A virtual environment is a self-contained directory that contains a Python installation and additional packages. Using venv, you can create multiple virtual environments, each with its own dependencies, without affecting the global Python installation.

2. Creating a Virtual Environment

To create a virtual environment using venv, follow these steps:

  1. Open your command prompt or terminal.
  2. Navigate to the directory where you want to create your project.
  3. Run the following command to create a virtual environment named myproject:
python -m venv myproject

This command creates a folder named myproject containing the virtual environment. Inside, you'll find directories like Include, Lib, and Scripts, which hold the Python interpreter and libraries specific to this environment.


3. Activating the Virtual Environment

Before installing packages or running Python scripts, activate the virtual environment:

  1. Windows:
myproject\Scripts\activate
  1. macOS/Linux:
source myproject/bin/activate

Upon activation, your command prompt will change to indicate the active environment, typically displaying (myproject) before the prompt.


4. Installing Packages

With the virtual environment activated, you can install packages using pip:

pip install package_name

These packages will be installed only within the myproject environment, ensuring project-specific dependencies.

5. Deactivating the Virtual Environment

Once you're done working, deactivate the virtual environment by running:

deactivate

This command returns you to the global Python environment.

6. Deleting a Virtual Environment

If you no longer need a virtual environment, you can delete its folder:

rm -rf myproject

This removes the environment and all its dependencies.


Conclusion

Using Python's venv module to create and manage virtual environments is a best practice for maintaining clean and manageable projects. It ensures that each project has its own dependencies, preventing conflicts and simplifying development workflows.

14. How to Create and Use Python Virtual Environments with venv

coldshadow44 on 2025-10-11



(0)





Showing comments related to this post.




Member's Sites: