Python Tutorial: VENV (Windows) - How to Use Virtual Environments with the Built-In venv Module
Table of Contents
Introduction
In this tutorial, we will explore how to use virtual environments in Python on Windows using the built-in venv
module. Virtual environments are essential for managing dependencies in Python projects, allowing you to create isolated spaces for different projects without conflicts. By the end of this guide, you'll know how to create, activate, and remove virtual environments effectively.
Step 1: Install Python
Before using venv
, ensure that Python is installed on your system.
- Download the latest version of Python from the official website: python.org.
- During installation, check the box that says "Add Python to PATH" to make it accessible from the command line.
Step 2: Open Command Prompt
To create a virtual environment, you need to access the Command Prompt.
- Press
Windows + R
to open the Run dialog. - Type
cmd
and hit Enter to launch the Command Prompt.
Step 3: Create a Virtual Environment
Now, let’s create a virtual environment.
-
Navigate to your desired project directory using the
cd
command. For example:cd C:\path\to\your\project
-
Use the following command to create a virtual environment:
python -m venv myenv
- Replace
myenv
with your desired environment name.
- Replace
Step 4: Activate the Virtual Environment
Activation is necessary to use the virtual environment.
- Run the following command:
myenv\Scripts\activate
- Once activated, your command prompt will show the environment name, indicating that you are now working within that virtual environment.
Step 5: Install Packages
With the virtual environment activated, you can install packages using pip
.
- For example, to install Flask, use:
pip install Flask
- This ensures that Flask is installed only within your virtual environment.
Step 6: Deactivate the Virtual Environment
When finished working, you can deactivate the environment.
- Simply type:
deactivate
- This will return you to the global Python environment.
Step 7: Remove a Virtual Environment
If you no longer need a virtual environment, you can remove it.
- Ensure the environment is deactivated.
- Delete the environment folder manually:
- Navigate to your project directory and delete the folder (e.g.,
myenv
).
- Navigate to your project directory and delete the folder (e.g.,
Conclusion
In this tutorial, you learned how to set up and manage Python virtual environments using the venv
module on Windows. Key steps include creating, activating, and removing environments, as well as installing packages. Virtual environments are crucial for maintaining clean and organized project dependencies. As a next step, consider exploring how to manage different package versions and using requirements.txt
for tracking dependencies across projects.