chapter six

6 Creating and Managing Python Virtual Environments

 

This chapter covers

  • Why virtual environments matter (and what goes wrong without them)
  • Creating a virtual environment with python3.13 -m venv
  • Activating and deactivating on macOS
  • Installing packages with pip
  • Freezing and restoring dependencies with requirements.txt

When you are writing a Python program, you can save a lot of time and effort by using prewritten code, available as Python packages. But before you install any Python packages for your chatbot project, you need to understand virtual environments. This concept may seem tedious at first, but it is one of those foundational practices that separates clean, professional Python development from chaos. By the end of this chapter, you will be able to create isolated Python environments for any project, install packages safely, and share your exact setup with anyone---a skill you will use in every chapter that follows.

6.1 Why Virtual Environments Matter

Imagine you have three different projects on your computer: an AI chatbot, a web scraper, and a data analysis tool. Each project needs different Python packages---reusable bundles of code written by other developers that add new capabilities to your programs. A package (also called a library) might provide tools for making web requests, building user interfaces, or connecting to an AI model. You do not need to write everything from scratch; you install packages that other people have already built and tested.

6.1.1 Three reasons every developer uses them

6.2 Creating a Virtual Environment

6.2.1 Step 1: Navigate to your project folder

6.2.2 Step 2: Create the virtual environment

6.2.3 Understanding the command

6.2.4 What is inside the venv folder?

6.3 Activating and Deactivating

6.3.1 Activating the virtual environment

6.3.2 Verifying activation

6.3.3 Deactivating the environment

6.4 Installing Packages with pip

6.4.1 What is pip?

6.4.2 Installing the Ollama Python package

6.4.3 Installing Streamlit

6.4.4 Checking installed packages

6.5 Freezing and Restoring Dependencies

6.5.1 Creating requirements.txt

6.5.2 Restoring an environment from requirements.txt

6.5.3 Keeping requirements.txt updated

6.5.4 The complete virtual environment workflow

6.6 Summary

6.7 Exercises