Skip to content
PythonTesting, Quality, and Packagingbeginner28 min read

Virtual Environments and pip

Create isolated Python environments, install and manage packages with pip, and reproduce project dependencies reliably.

In this lesson, you will learn

  • ✓Explain why Python projects use virtual environments.
  • ✓Create, activate, deactivate, and verify a virtual environment on common operating systems.
  • ✓Install, inspect, upgrade, and remove packages with pip.
  • ✓Use requirements.txt to record and reinstall project dependencies.
  • ✓Troubleshoot common interpreter, installation, and dependency problems.

1. What are packages, pip, and virtual environments?

A Python module is a file containing Python code that can be imported. A Python package can organize modules into a reusable distribution. In everyday development, the word package also commonly refers to software that can be installed into a Python environment.

A third-party package is software that is not part of Python's standard library. Examples include requests for making HTTP requests and pytest for running tests.

pip is Python's commonly used package installer. It can download packages from a package index, install their dependencies, upgrade existing installations, and remove packages.

A virtual environment is an isolated Python environment associated with a base Python installation. It has its own location for installed packages and its own Python executable or interpreter link. Packages installed into one virtual environment are normally separate from packages installed into another.

Imagine two projects. Project A needs one version of a library, while Project B needs a different version. Separate virtual environments help each project manage its own dependencies without forcing both projects to share the same installed version.

Creating a virtual environment does not copy every system component into a completely independent operating system. It uses a base Python installation and isolates the project's installed packages and related environment configuration.

Understand the tools

Understand the tools
text
Python interpreter: runs Python code
pip: installs and manages packages
venv: creates virtual environments
.venv/: a common folder name for a project's environment
Output
Each tool has a different responsibility.

The interpreter executes Python programs. pip manages package installations for the Python environment it is associated with. venv is included in Python's standard library and creates virtual environments. .venv is simply a conventional directory name; you can choose another name. The environment directory belongs to the development setup and normally should not be committed to version control.

Note

A virtual environment does not replace Python itself. You need a suitable base Python installation to create it.

2. Create and activate a virtual environment

Start by opening a terminal in your project directory. A terminal is where you run shell commands; commands such as python -m venv .venv are not ordinary Python statements to paste into a .py file.

The venv module creates a virtual environment. The final argument specifies the directory in which it will be created. The common name .venv keeps the environment associated with the project.

The command depends slightly on the operating system and how Python was installed. On Windows, py -m venv .venv is commonly used with the Python launcher. On macOS or Linux, python3 -m venv .venv is commonly used. If the python command already points to the intended Python 3 interpreter, python -m venv .venv is also appropriate.

After creation, activate the environment in your current shell. Activation adjusts the shell's command lookup path so that python and installed command-line tools normally resolve to the virtual environment.

Activation commands differ by shell. PowerShell and Command Prompt use different Windows commands; Bash and Zsh use the POSIX activation script. Do not use a PowerShell command in Command Prompt or vice versa.

You do not strictly have to activate an environment. You can invoke its Python executable directly. Activation is convenient because it makes ordinary python and pip commands use the environment.

Create the environment

Create the environment
bash
# Windows
py -m venv .venv
 
# macOS or Linux
python3 -m venv .venv
Output
A .venv directory is created in the current project directory.

Run the command for your operating system in the terminal, not inside the Python interpreter. The venv module creates the environment directory and its configuration. The directory contains a platform-specific interpreter location and package-installation directories. If Python cannot be found, check your installation and command name. If environment creation fails because the venv support is missing on Linux, you may need to install the appropriate venv package using your distribution's package manager.

Note

You normally create an environment once per project setup and reactivate it when you return. You do not need to create a new environment every time you open the project.

3. Verify the interpreter and install packages with pip

One of the most common Python environment problems is installing a package into one interpreter and running the program with another. For example, pip might install a library into your system Python while your editor runs a virtual environment that cannot see it.

The reliable habit is to associate pip with the interpreter you intend to use. The command python -m pip runs pip through the Python executable selected by python. When the environment is active, this normally installs packages into that environment.

After activating .venv, install a package with python -m pip install requests. You can replace requests with the name of another package that you need.

Use python -m pip --version to inspect the pip version and the location from which it is running. Use python -c "import sys; print(sys.executable)" to inspect the selected interpreter path.

The sys module also lets you check whether the current interpreter is running inside a virtual environment. A reliable check is sys.prefix != sys.base_prefix. It is more dependable than guessing from the executable filename.

Package names used by pip are not always identical to import names. For example, a distribution name and the module name used in import statements may differ. Always follow the package's documentation for its correct installation and import instructions.

Check which Python is running

Check which Python is running
python
import sys
 
print(sys.executable)
print(sys.prefix != sys.base_prefix)
Output
The first line is the interpreter path. The second line is True when running inside a standard virtual environment.

sys.executable identifies the Python executable being used. Inside a standard virtual environment, sys.prefix points to the environment while sys.base_prefix points to the base Python installation. Therefore, sys.prefix != sys.base_prefix evaluates to True inside a standard virtual environment and False in a normal base interpreter. The actual path varies across computers and operating systems. This check is more meaningful than testing whether the executable path happens to contain the word python.

Note

Prefer python -m pip over a bare pip command when you want to make the interpreter-to-installer relationship explicit.

4. Inspect, upgrade, uninstall, and diagnose packages

pip provides commands for inspecting installed packages and managing their versions. You can list packages, show metadata, check dependency consistency, upgrade a package, or uninstall a package.

python -m pip list displays installed distributions in the selected environment. python -m pip show PACKAGE displays metadata for one installed distribution. python -m pip check checks whether installed packages have compatible declared dependencies.

Use python -m pip uninstall PACKAGE to remove a distribution from the selected environment. pip will normally ask for confirmation unless you provide an option that changes that behavior.

Use python -m pip install --upgrade PACKAGE to request an upgrade. Upgrading a package can also affect dependency resolution, so test the project after changing important dependencies.

If you see ModuleNotFoundError, first verify that the interpreter running your program is the same one into which you installed the package. A package may be installed successfully in one environment and still be unavailable in another.

If installation reports a permission error, avoid immediately using administrator privileges or sudo. First check whether you should be installing into a project virtual environment. Installing into a system-managed Python environment can interfere with operating-system tools.

If a package cannot be installed, check the package name, Python version requirements, platform compatibility, network access, and the full pip error message. Some packages include native extensions and may require platform-specific dependencies.

Inspect the environment

Inspect the environment
bash
python -m pip list
python -m pip show requests
python -m pip check
Output
A package list, requests metadata if installed, and a dependency-consistency result.

pip list shows installed distributions and their versions. pip show requests reports information about requests if it is installed in the selected environment. pip check reports dependency conflicts if installed distributions declare incompatible requirements. The exact package list and results depend on the environment. If requests is not installed, pip show requests will report that the package was not found.

Caution

Use pip commands with the intended environment selected. Installing or uninstalling packages in the wrong interpreter is a common cause of confusing import errors and dependency conflicts.

5. Manage dependencies with requirements.txt

A project often depends on more than one third-party package. Instead of asking every developer to remember each installation command, you can record dependencies in a requirements.txt file.

A requirements file commonly contains one requirement per line. For example, requests==2.32.3 asks for that exact distribution version. You can also use version ranges when the project allows compatible updates.

To install the listed requirements, run python -m pip install -r requirements.txt after activating the project's environment.

The command python -m pip freeze prints installed distributions in a format that can be used as a requirements file. You can redirect that output into a file with python -m pip freeze > requirements.txt.

Be aware that pip freeze records installed distributions, including transitive dependencies, in the current environment. If that environment contains unrelated packages, the generated file may include packages the project does not actually need.

For a small learning project, a manually maintained requirements.txt file is often sufficient. For larger applications, dependency constraints and lock-file workflows may provide more deliberate control over reproducibility.

Virtual environments are generally not portable directories that you copy between machines. Their scripts and interpreter references can contain environment-specific paths. Recreate the environment at the new location and reinstall the dependencies instead.

Example requirements.txt

Example requirements.txt
text
requests==2.32.3
pytest>=8,<9
Output
Two dependency requirements: a pinned requests version and a pytest version range.

Each non-comment line describes a requirement for a distribution. requests==2.32.3 requests one exact version. pytest>=8,<9 allows versions at least 8 but below 9, subject to other compatibility constraints. The versions are illustrative and should be checked against the project's supported Python versions and compatibility needs. Save these lines in a file named requirements.txt in the project directory.

Note

Keep dependency files in version control, but do not commit the .venv directory. A clean checkout should be able to recreate the environment by creating a new virtual environment and installing the recorded dependencies.

6. Complete project workflow and common problems

A repeatable setup follows a predictable sequence: open the project directory, create the virtual environment if needed, activate it, install dependencies, and run the program or tests.

The environment directory is a local development artifact. Add .venv/ to .gitignore so that Git does not track its installed packages and environment-specific files.

A typical project layout might contain main.py, requirements.txt, .gitignore, and .venv/. The .venv folder is created locally; main.py and requirements.txt are project files.

If the terminal uses the right interpreter but your editor does not, select the interpreter located inside your project's .venv directory in the editor's Python settings.

If the python command is unavailable, the Python installation or PATH may need attention. On Windows, the py launcher may be available even when python is not. On Linux, python3 is commonly used.

If pip is missing, first check that you are using the intended Python installation. Some Python installations provide ensurepip, while some Linux distributions package venv and pip separately. Follow the operating system's supported installation instructions.

If activation is inconvenient or unavailable, run the environment's interpreter directly. For example, Windows uses .venv\Scripts\python.exe and POSIX systems use .venv/bin/python.

Before concluding that a package is broken, compare the interpreter path used for installation with the interpreter path used to run the program. This simple check resolves many environment-related problems.

Typical project setup

Typical project setup
bash
# 1. Create the environment if it does not exist
python -m venv .venv
 
# 2. Activate it (POSIX shell)
source .venv/bin/activate
 
# 3. Install dependencies
python -m pip install -r requirements.txt
 
# 4. Run the program
python main.py
Output
The environment is created, dependencies are installed, and main.py is run using the selected interpreter.

This sequence shows a POSIX shell workflow. On Windows, use the appropriate creation and activation commands. The creation step is normally performed once per local environment; if .venv already exists and is healthy, activate it rather than recreating it. The requirements file must exist and contain valid dependencies before step 3. The main.py file must exist for step 4. The actual output depends on the program and its dependencies.

Caution

Do not copy a virtual environment from one computer to another and assume it will work. Recreate it in the destination environment and reinstall dependencies from your project's dependency file.

Common pitfalls to avoid

Real debugging lessons and exact syntax contrasts to avoid runtime bugs

#1 Installing a package globally when the project should use a virtual environment.

Why it happens: Installing packages globally can create version conflicts between projects; a virtual environment isolates each project's dependencies.

Incorrect Approach
script.py
python
Activate .venv before installing requests so the package is installed into the project environment.
Correct Solution
script.py
python
Create and activate the project's virtual environment, then use python -m pip install PACKAGE.

Key takeaway: Create and activate the project's virtual environment, then use python -m pip install PACKAGE.

#2 Using a different interpreter to run the program than the one used to install its packages.

Why it happens: Packages are installed into the environment associated with the pip/interpreter command, so running another interpreter may not find them.

Incorrect Approach
script.py
python
A package installed in .venv may not be importable when the program runs using the system Python.
Correct Solution
script.py
python
Check sys.executable and python -m pip --version. Select the project's virtual environment interpreter in your editor.

Key takeaway: Check sys.executable and python -m pip --version. Select the project's virtual environment interpreter in your editor.

#3 Treating shell commands as Python code.

Why it happens: Shell commands such as python -m venv .venv and pip install requests belong in a terminal, not inside a Python source file or interactive expression.

Incorrect Approach
script.py
python
Do not put python -m pip install requests directly into a Python script as if it were a Python statement.
Correct Solution
script.py
python
Run commands such as python -m venv .venv in a terminal. Use Python code only for statements intended to execute inside a .py file or Python interpreter.

Key takeaway: Run commands such as python -m venv .venv in a terminal. Use Python code only for statements intended to execute inside a .py file or Python interpreter.

#4 Assuming activation commands are identical on every operating system and shell.

Why it happens: Activation commands differ between Windows shells and POSIX shells; use the command appropriate for the terminal and environment.

Incorrect Approach
script.py
python
PowerShell uses .venv\Scripts\Activate.ps1; Bash normally uses source .venv/bin/activate.
Correct Solution
script.py
python
Choose the activation command for PowerShell, Command Prompt, Bash, or Zsh.

Key takeaway: Choose the activation command for PowerShell, Command Prompt, Bash, or Zsh.

#5 Committing the .venv directory to version control.

Why it happens: A .venv folder contains environment-specific files and can be large or platform-dependent; recreate it from dependency metadata instead of committing it.

Incorrect Approach
script.py
python
Commit requirements.txt so other developers can recreate the environment.
Correct Solution
script.py
python
Add .venv/ to .gitignore and commit the project code and dependency instructions instead.

Key takeaway: Add .venv/ to .gitignore and commit the project code and dependency instructions instead.

#6 Assuming pip freeze lists only direct project dependencies.

Why it happens: pip freeze reports installed distributions in the environment, including transitive dependencies, not only packages directly chosen by the project.

Incorrect Approach
script.py
python
A global environment may contain many unrelated packages that should not be included in a small project's requirements file.
Correct Solution
script.py
python
Review the output because it records installed distributions in the current environment, including transitive dependencies and potentially unrelated packages.

Key takeaway: Review the output because it records installed distributions in the current environment, including transitive dependencies and potentially unrelated packages.

#7 Using sudo or administrator permissions immediately to solve an installation error.

Why it happens: Permission errors often indicate the wrong environment or interpreter; using administrator privileges immediately can modify the wrong installation or create security risks.

Incorrect Approach
script.py
python
A permission error may indicate that pip is targeting a protected system installation rather than the intended project environment.
Correct Solution
script.py
python
Check the selected interpreter and use a project virtual environment when appropriate. Follow the operating system's package-management guidance for system Python.

Key takeaway: Check the selected interpreter and use a project virtual environment when appropriate. Follow the operating system's package-management guidance for system Python.

#8 Assuming an environment can be moved between computers like an ordinary source folder.

Why it happens: Virtual environments contain paths and platform-specific artifacts, so they are normally recreated on each machine from dependency specifications.

Incorrect Approach
script.py
python
Create a new .venv and run python -m pip install -r requirements.txt.
Correct Solution
script.py
python
Recreate the environment at its destination and reinstall dependencies using the dependency file.

Key takeaway: Recreate the environment at its destination and reinstall dependencies using the dependency file.

Ready for hands-on challenges?

Test your skills with shuffled coding challenges in the Practice Arena.

Practice Arena →

Technical and placement interview questions

Frequently tested interview questions with detailed, full answers (click to expand)

Q1:What is a virtual environment in Python?
Answer:
A virtual environment is an isolated Python environment associated with a base Python installation. It has its own package installation location and helps projects use different dependencies without interfering with each other.
Q2:What is pip?
Answer:
pip is Python's commonly used package installer. It can install, upgrade, inspect, and uninstall distributions and can install requirements from a file.
Q3:What is the difference between venv and pip?
Answer:
venv creates a virtual environment. pip manages package installations in the Python environment with which it is associated.
Q4:How do you create and activate a virtual environment?
Answer:
Create it with python -m venv .venv or the appropriate platform-specific Python command. Activate it with the activation script for the current shell, such as .venv\Scripts\Activate.ps1 in PowerShell or source .venv/bin/activate in Bash.
Q5:Why use python -m pip instead of pip?
Answer:
python -m pip runs pip using the selected Python interpreter, which helps ensure that packages are installed into the environment you intend to use.
Q6:What is requirements.txt used for?
Answer:
It records package requirements so pip can install them with python -m pip install -r requirements.txt. This helps developers recreate a project's dependencies.
Q7:What is the difference between pip list and pip freeze?
Answer:
pip list displays installed distributions in a human-readable list. pip freeze outputs installed distribution requirements and versions in a format commonly used to create a requirements file.
Q8:How can you verify which Python interpreter is running?
Answer:
Run import sys followed by print(sys.executable), or use python -c "import sys; print(sys.executable)" in the terminal. The resulting path identifies the interpreter.
Q9:How do you troubleshoot ModuleNotFoundError after installing a package?
Answer:
Check the interpreter path used by the program, the environment targeted by pip, the package's installation status, and the correct import name. The program may be running with a different interpreter.
Q10:Why should a virtual environment normally not be committed to Git?
Answer:
It contains local environment files and installed packages that can be regenerated. Commit the source code and dependency instructions, ignore .venv/, and recreate the environment on another machine.

Key takeaways

  • Virtual environments help isolate a project's dependencies.
  • venv creates environments, while pip installs and manages packages.
  • Use the activation command appropriate for your operating system and shell.
  • Use python -m pip to associate package management with the selected interpreter.
  • Check sys.executable and sys.prefix != sys.base_prefix when diagnosing environment issues.
  • Use requirements.txt to document dependencies and help recreate the environment.
  • Review pip freeze output instead of assuming it contains only direct project dependencies.
  • Ignore .venv/ in version control and recreate environments on other machines.
  • When imports fail, first check whether installation and execution use the same interpreter.
Was this lesson helpful?
Found an error? Report an issue

Related Topics & Next Steps

4 Recommended Lessons

Strengthen your Python foundation with these complementary core lessons: