Skip to content

Virtual Environments and Packages

💡
Before you start

You need Python installed, and to know how to run a .py file. If python3 --version in a terminal prints a version number, you are ready. If it does not — or if you have never opened a terminal — do Getting Started with Python first; it installs Python and runs your first program, and takes about fifteen minutes. Nothing else is needed: no account, no payment, no extra software.

Why Virtual Environments?

Different projects need different package versions. Project A might need requests 2.28 while Project B needs requests 2.31. Without isolation, installing one breaks the other.

Virtual environments create isolated Python installations per project, each with its own packages. This is a fundamental best practice — every serious Python project uses one.

⚠️
Never install packages globally

Running pip install without a virtual environment installs packages system-wide, which can break your OS tools and conflict between projects. Always activate a venv first.

Creating a Virtual Environment

1
Create the virtual environment:
python3 -m venv myproject-env

This creates a myproject-env/ directory containing an isolated Python installation.

2
Activate it:
# Linux / macOS
source myproject-env/bin/activate

# Windows
myproject-env\Scripts\activate

Your prompt changes to show the active environment: (myproject-env) $

3
Deactivate when done:
deactivate
💡
Common convention

Most developers name their virtual environment venv or .venv and create it inside the project directory. Add it to .gitignore — never commit the venv folder to version control.

Installing Packages with pip

# Install a package
pip install requests

# Install a specific version
pip install requests==2.31.0

# Install minimum version
pip install "requests>=2.28"

# Upgrade a package
pip install --upgrade requests

# Uninstall a package
pip uninstall requests

# Show installed packages
pip list

# Show details about a package
pip show requests

requirements.txt

A requirements.txt file lists all packages your project needs, making it easy for others (or your future self) to recreate the environment:

Creating requirements.txt

# Export current packages to requirements.txt
pip freeze > requirements.txt

The file looks like:

certifi==2024.2.2
charset-normalizer==3.3.2
idna==3.6
requests==2.31.0
urllib3==2.2.1

Installing from requirements.txt

# Install all packages from requirements.txt
pip install -r requirements.txt
💡
Hand-written vs frozen requirements

pip freeze includes every sub-dependency with exact versions. For simpler projects, you can hand-write requirements.txt with just your direct dependencies: requests>=2.28

Project Setup Workflow

Here's the standard workflow for starting a new Python project:

# 1. Create project directory
mkdir my-project && cd my-project

# 2. Create virtual environment
python3 -m venv .venv

# 3. Activate it
source .venv/bin/activate

# 4. Install packages you need
pip install requests python-dotenv

# 5. Save dependencies
pip freeze > requirements.txt

# 6. Create .gitignore
echo ".venv/" > .gitignore
echo "__pycache__/" >> .gitignore
echo "*.pyc" >> .gitignore
echo ".env" >> .gitignore

# 7. Start coding!
touch main.py

Cloning Someone Else's Project

# 1. Clone the repository
git clone https://example.com/project.git
cd project

# 2. Create your own virtual environment
python3 -m venv .venv
source .venv/bin/activate

# 3. Install the project's dependencies
pip install -r requirements.txt

# 4. Run the project
python main.py

Popular Python Packages

  • requests — HTTP requests (API calls, web scraping)
  • flask — Lightweight web framework
  • python-dotenv — Load environment variables from .env files
  • pytest — Testing framework
  • black — Code formatter
  • rich — Beautiful terminal output (colors, tables, progress bars)
  • click — Build command-line interfaces
  • pillow — Image processing

Useful pip Commands Reference

# Search for packages (use pypi.org for browsing)
pip search package-name        # Deprecated, use website

# Check for outdated packages
pip list --outdated

# Install from a Git repository
pip install git+https://github.com/user/repo.git

# Install in development/editable mode
pip install -e .

# Check for dependency conflicts
pip check

# Show where packages are installed
pip show -f requests

Common Pitfalls

⚠️
Don't commit your venv folder

Virtual environments contain thousands of files specific to your OS and Python version. Always add .venv/ to .gitignore and share requirements.txt instead.

# .gitignore for Python projects
.venv/
__pycache__/
*.pyc
*.pyo
.env
*.egg-info/
dist/
build/

Now Do It Yourself: Five Steps

A virtual environment is a private Python for one project, so two projects that need different versions of the same package cannot break each other. You will build one, prove it is isolated, install into it, and record what it contains. Every output below is exactly what Python printed, except where noted in step 4.

1
Create the environment

Go: open a terminal and make a folder for the project: mkdir ~/myproject, then cd ~/myproject.

Do: run python3 -m venv myenv. On Windows use python -m venv myenv.

You should see: no output, and after a few seconds a new myenv folder. Look inside with ls myenv (dir myenv on Windows): it contains its own bin folder — Scripts on Windows — holding python, pip and activate. That is the whole idea: a complete private copy.

If not: on Debian and Ubuntu, The virtual environment was not created successfully because ensurepip is not available means one extra package is missing; the message itself tells you to install python3-venv. That is a genuine gap in those distributions, not a mistake you made.

2
Prove it really is a separate Python

Go: stay in ~/myproject. Do not activate anything yet — this step is the comparison.

Do: run these two commands one after the other.

python3 -c "import sys; print(sys.prefix)"
./myenv/bin/python -c "import sys; print(sys.prefix)"

You should see: two different paths. The first is your system Python — on many Linux machines /usr. The second ends in /myproject/myenv. Same command, two Pythons, and they share nothing.

If not: if both print the same path, you are already inside an activated environment from earlier — run deactivate and try again. On Windows the second command is myenv\Scripts\python -c "import sys; print(sys.prefix)", with backslashes.

3
Activate it, and see that it starts empty

Go: same folder.

Do: run source myenv/bin/activate on Linux or macOS, or myenv\Scripts\activate on Windows. Then run pip list.

You should see: your prompt gains a (myenv) prefix — that is how you know which Python you are talking to. pip list then prints nothing, or only pip's own packaging tools. A fresh environment installs nothing you did not ask for.

If not: source: command not found means you are in a shell that spells it differently — try . myenv/bin/activate with a leading dot and a space. On Windows PowerShell, cannot be loaded because running scripts is disabled is a policy setting, not a broken install; the standard fix is to run PowerShell as administrator once and allow local scripts.

4
Install a package into it

Go: same terminal, with (myenv) showing in the prompt. This step needs an internet connection.

Do: run pip install requests, then python -c "import requests; print(requests.__version__)".

You should see: pip downloading and finishing with a line beginning Successfully installed and naming requests with its version, then that version printed on its own. This is the one step on this page not run on our machine — it needs network access we deliberately do not use — so treat the exact wording of pip's output as approximate. The check that matters is the second command printing a version rather than an error.

If not: ModuleNotFoundError: No module named 'requests' after a successful install almost always means the install went to a different Python. Run pip -V — the path it prints must be inside your myenv folder. If it is not, the environment is not activated, and you have just installed into your system Python instead, which is exactly what virtual environments exist to avoid.

5
Record what the project needs, then step back out

Go: same terminal, still activated.

Do: run pip freeze > requirements.txt, look at it with cat requirements.txt, then run deactivate.

You should see: a file listing each installed package pinned to an exact version, one per line. Then deactivate removes the (myenv) prefix and you are back on your system Python. Anyone can now rebuild your exact environment with pip install -r requirements.txt — that file, not the myenv folder, is what you share.

If not: an empty requirements.txt means nothing is installed yet — in a brand-new environment pip freeze genuinely outputs zero lines, which is correct rather than broken. And never commit the myenv folder itself to version control: it is large, machine-specific, and rebuilt in seconds from the requirements file.

🎉
Check yourself before moving on

Without scrolling up: pip install reported success, but importing the package fails. What is the first thing to check, and with which command? Answer: whether the environment is actually activated — run pip -V and confirm the path it prints is inside your myenv folder. If it is not, the package went into your system Python.

Now do it without the page: make a second project folder with its own environment, and confirm that a package installed in the first one is not importable in the second. That failure is the isolation working, and seeing it once is what makes the idea stick.

Summary

  • Virtual environments isolate project dependencies: python3 -m venv .venv
  • Activate with source .venv/bin/activate, deactivate with deactivate
  • pip install package installs packages; pip freeze > requirements.txt saves them
  • pip install -r requirements.txt recreates an environment from a file
  • Never install packages globally or commit the venv folder
  • Every Python project should have a virtual environment and a requirements.txt
🎉
Package management mastered!

You now have all the tools to manage Python projects professionally. With basics, intermediate skills, and proper tooling under your belt, you're ready to build real-world Python applications!