Python
Python

 

 

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.

 

By Aditya Bhuyan

I work as a cloud specialist. In addition to being an architect and SRE specialist, I work as a cloud engineer and developer. I have assisted my clients in converting their antiquated programmes into contemporary microservices that operate on various cloud computing platforms such as AWS, GCP, Azure, or VMware Tanzu, as well as orchestration systems such as Docker Swarm or Kubernetes. For over twenty years, I have been employed in the IT sector as a Java developer, J2EE architect, scrum master, and instructor. I write about Cloud Native and Cloud often. Bangalore, India is where my family and I call home. I maintain my physical and mental fitness by doing a lot of yoga and meditation.

Leave a Reply

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

error

Enjoy this blog? Please spread the word :)