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
  • Activating and deactivating a virtual environment 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; instead, you install packages that other people have already built and tested.

6.2 Creating a virtual environment

6.2.1 Navigate to your project folder

6.2.2 Create the virtual environment

6.2.3 Understanding the venv command

6.2.4 What is inside the venv folder?

6.3 Activating and deactivating a virtual environment

6.3.1 Activating the virtual environment

6.3.2 Verifying activation

6.3.3 Deactivating the virtual 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 the installed packages