How to Set Up and Use Python Virtual Environments

 

 

Introduction

Python virtual environments are isolated environments that allow you to manage dependencies for different projects without interference. Whether you’re working on a Flask app or a data science notebook, a virtual environment keeps your workspace clean and organized.

Objective

By the end of this tutorial, you’ll be able to:

  • Create a Python virtual environment
  • Activate and deactivate the environment
  • Install dependencies within the environment
  • Understand the structure of a virtual environment

Step-by-Step Code

# Step 1: Navigate to your project folder
mkdir myproject
cd myproject

# Step 2: Create a virtual environment
python -m venv env

# Step 3: Activate the environment
# On Windows:
env\Scripts\activate

# On macOS/Linux:
source env/bin/activate

# Step 4: Install a package (e.g., requests)
pip install requests

# Step 5: Freeze dependencies (optional)
pip freeze > requirements.txt

# Step 6: Deactivate the environment
deactivate

Program Structure & Explanation

Here’s what each part of the setup does:

  • mkdir myproject: Creates a new directory for your project.
  • python -m venv env: Initializes a virtual environment named env inside the project folder.
  • activate: Starts the virtual environment so that you can install packages locally.
  • pip install: Installs dependencies into the isolated environment.
  • pip freeze > requirements.txt: Saves a snapshot of installed packages for version control or sharing.
  • deactivate: Exits the virtual environment, returning to your system Python.

How to Run the Program

  1. Open your terminal or command prompt.
  2. Follow the steps above to create and activate your environment.
  3. Once inside the environment, install any libraries you need.
  4. Run your Python scripts like normal: python your_script.py
  5. When done, type deactivate to exit the environment.
© 2025 Learn Programming. All rights reserved.

 

Leave a Reply

Your email address will not be published. Required fields are marked *