DEV Community

Cover image for Python Virtual Environment Setup: Commands, Structure, and Sample Program πŸπŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»
Khushalsarode
Khushalsarode

Posted on • Edited on

Python Virtual Environment Setup: Commands, Structure, and Sample Program πŸπŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

Whether you're building data pipelines, web apps, or experimenting with AI models, managing project dependencies is crucial. That’s where Python virtual environments come into play.

πŸ“š Table of Contents

πŸ” What is a Python Virtual Environment?

A virtual environment is an isolated environment for Python projects. It allows you to manage dependencies separately for each project, preventing conflicts between libraries.

A virtual environment helps you keep each Python project separate on the same computer.

It lets you use specific versions of packages for each project without interfering with other projects or your system.

This logical separation makes it easy to manage multiple projects with different requirements at the same time.

Enter fullscreen mode Exit fullscreen mode

βš™οΈ Prerequisites

  • Ensure Python is installed:
python --version    # or python3 --version
Enter fullscreen mode Exit fullscreen mode

If not, download Python.

πŸ’» Virtual Environment Setup by OS

πŸ–₯ Windows

  1. Open Command Prompt or PowerShell
  2. Create a virtual environment
python -m venv env
Enter fullscreen mode Exit fullscreen mode

Replace env with your desired environment name.

.

πŸ”§ Creating a Python Virtual Environment with a Specific Version

Setting up a virtual environment with a specific Python version ensures your project dependencies remain isolated and compatible. Below are different ways to create a Environment using the version you want:

  • βœ… Using python3.x (Linux/macOS)
python3.10 -m venv venv
Enter fullscreen mode Exit fullscreen mode

This creates a virtual environment named venv using Python 3.10 (if installed).

  • βœ… Using py -3.x (Windows)
py -3.10 -m venv venv
Enter fullscreen mode Exit fullscreen mode

This is the preferred way on Windows when managing multiple Python versions via the Python Launcher (py).

  • Activate the environment
.\env\Scripts\activate
Enter fullscreen mode Exit fullscreen mode

or

  • Command Prompt : env\Scripts\activate.bat
  • Powershell : env\Scripts\Activate.ps1

🍎 macOS / 🐧 Linux

  1. Open Terminal
  2. Create the virtual environment
python3 -m venv env
Enter fullscreen mode Exit fullscreen mode
  1. Activate the environment
source env/bin/activate
Enter fullscreen mode Exit fullscreen mode

πŸ§ͺ Verify the Environment

  • which python # Linux/macOS
  • where python # Windows

You should see the path pointing to your local env folder.

πŸ“ Virtual Environment Directory Structure

project-folder/
β”‚
β”œβ”€β”€ env/                     # Virtual environment directory
β”‚   β”œβ”€β”€ bin/ or Scripts/     # Executables (python, pip)
β”‚   β”œβ”€β”€ include/             # Header files
β”‚   β”œβ”€β”€ lib/                 # Installed packages
β”‚   └── pyvenv.cfg           # Config file
β”‚
β”œβ”€β”€ main.py                  # Your Python script
└── requirements.txt         # Project dependencies (optional)
Enter fullscreen mode Exit fullscreen mode

🐾 Steps to Setup a Project

  • Create a project folder
mkdir myproject && cd myproject
Enter fullscreen mode Exit fullscreen mode
  • Create the virtual environment
python -m venv env
Enter fullscreen mode Exit fullscreen mode
  • Activate it
### Windows
.\env\Scripts\activate

### macOS/Linux
source env/bin/activate
Enter fullscreen mode Exit fullscreen mode
  • Install packages
pip install requests
Enter fullscreen mode Exit fullscreen mode
  • Freeze requirements
pip freeze > requirements.txt
Enter fullscreen mode Exit fullscreen mode
  • Run your Python program
python main.py
Enter fullscreen mode Exit fullscreen mode

After you activate environment it will show as shown in image:
Virtual Env Sample

🧾 Sample Program: main.py

import requests

def getpost():
    # Make a GET request to a public API
    url = "https://jsonplaceholder.typicode.com/posts/1"
    response = requests.get(url)

    # Print the response content Json
    #print(response.json())
    if response.status_code == 200:
        print("Request was successful!")
        data = response.json()
        print("User ID{user_id} Title: {title} Body: {body}".format(user_id=data['userId'], title=data['title'], body=data['body']))
    else:
        print("Request failed with status code:", response.status_code)
    # Check the status code
    print(f"Status Code: {response.status_code}")

if __name__ == "__main__":
    getpost()
Enter fullscreen mode Exit fullscreen mode

πŸ’‘ Bonus Tips

  • To deactivate the environment:
deactivate
Enter fullscreen mode Exit fullscreen mode
  • To delete the virtual environment:
rm -rf env     # macOS/Linux
rmdir /s env   # Windows
Enter fullscreen mode Exit fullscreen mode
  • Use requirements.txt to share dependencies with teammates:
pip install -r requirements.txt
Enter fullscreen mode Exit fullscreen mode

Conclusion

Using a virtual environment keeps your Python projects clean and manageable. It’s an essential skill for every developer.

One does not simply pip install without a virtual environment

Top comments (0)