Creating and Activating Virtual Environments Using venv
Course: Python Training
Topic: Creating and Activating Virtual Environments Using venv
Course Link: Python Training Course
Demo Link: Register for a Course Demo
Website: JustAcademy
1. Introduction to Virtual Environments
A virtual environment in Python is an isolated environment that allows a project to use its own Python interpreter reference and installed packages without normally interfering with packages installed in other environments. Virtual environments are especially useful when different projects require different versions of the same library.
Python provides the built-in venv module to create virtual environments. It is included with standard Python installations and usually does not require installing an additional environment-management package.
For example, one project might require Django 4.x while another requires Django 5.x. Installing both projects' dependencies globally can create conflicts. Using separate virtual environments lets each project manage its own dependencies.
Learning Objectives
- Understand virtual environments and why they are important.
- Learn how the
venv module works.
- Create a virtual environment on Windows, macOS, and Linux.
- Activate and deactivate a virtual environment.
- Install and manage packages using
pip.
- Verify that Python and pip are using the correct environment.
- Save and reinstall dependencies using a requirements file.
- Troubleshoot common virtual environment errors.
2. What Is a Virtual Environment?
A virtual environment is a project-specific environment that separates installed Python packages from the default Python environment. It allows developers to manage dependencies independently for different applications.
When a virtual environment is activated, the shell is configured to use its Python executable and package installer by default. Packages installed with that environment's pip are generally installed into its own package directory.
Example Scenario
| Project |
Dependency Requirement |
Environment |
| Project A |
Django 4.x |
.venv-project-a |
| Project B |
Django 5.x |
.venv-project-b |
| Project C |
Flask and Requests |
.venv-project-c |
Each project can manage its dependencies independently, reducing the chance that installing a package for one project will disrupt another.
3. Why Do We Need Virtual Environments?
3.1 Dependency Isolation
Different projects can use different versions of the same package without requiring one shared global version.
3.2 Avoiding Package Conflicts
Installing or upgrading a library for one project does not normally change the corresponding library in another virtual environment.
3.3 Easier Collaboration
A project can maintain a dependency list that teammates use to recreate a similar development environment.
3.4 Cleaner Development Setup
Keeping project dependencies separate reduces unnecessary changes to the system-wide Python installation.
3.5 Reproducible Project Setup
A requirements file can record the dependencies needed by a project. Another developer can create a new virtual environment and install those packages to reproduce the intended setup, subject to Python version, platform, and dependency availability.
4. Understanding the venv Module
The venv module is part of Python's standard library. It creates a directory containing the files needed for a virtual environment.
The general command is:
python -m venv environment_name
Here:
python identifies the Python interpreter used to create the environment.
-m tells Python to run a module as a script.
venv is the module that creates the virtual environment.
environment_name is the directory where the environment will be created.
A commonly recommended directory name is .venv, although names such as venv or myenv can also be used.
5. Checking Whether Python Is Installed
Before creating a virtual environment, verify that Python is installed and accessible from the terminal.
Windows
python --version
If the Python launcher is available, you can also run:
py --version
macOS and Linux
python3 --version
Example output:
Python 3.12.0
The exact version depends on your installation. If the command is not recognized, install Python or correct your PATH configuration before proceeding.
6. Creating a Project Directory
It is good practice to create a dedicated directory for each Python project and create its virtual environment inside that directory.
Example: Create a Project Folder
On Windows Command Prompt:
mkdir python_project
cd python_project
On macOS or Linux:
mkdir python_project
cd python_project
Both command examples create a directory named python_project and move the terminal into it.
7. Creating a Virtual Environment on Windows
Open Command Prompt or PowerShell in the project directory.
Using the Python Launcher
py -m venv .venv
Using python
python -m venv .venv
Either command creates a virtual environment named .venv, provided the selected interpreter supports the venv module.
Expected Directory Structure
python_project/
.venv/
Include/
Lib/
Scripts/
pyvenv.cfg
The exact directory contents can vary by Python version and platform. On Windows, the environment's executables and activation scripts are generally stored in the Scripts directory.
8. Creating a Virtual Environment on macOS and Linux
Open a terminal in your project directory and run:
python3 -m venv .venv
Python creates the virtual environment directory and the required environment files.
Typical Directory Structure
python_project/
.venv/
bin/
include/
lib/
pyvenv.cfg
On these platforms, the environment's Python executable and activation scripts are usually located inside .venv/bin/.
9. Activating a Virtual Environment
Creating a virtual environment does not automatically activate it in your current terminal. Activation adjusts the shell environment so commands such as python and pip normally refer to the virtual environment.
9.1 Windows Command Prompt
.venv\Scripts\activate.bat
9.2 Windows PowerShell
.\.venv\Scripts\Activate.ps1
9.3 macOS and Linux Using Bash or Zsh
source .venv/bin/activate
After successful activation, the terminal prompt often displays the environment name.
Example:
(.venv) C:\python_project>
The displayed prompt is a helpful indication, but verifying the interpreter path is more reliable.
10. Verifying the Active Virtual Environment
After activation, confirm that Python points to the intended environment.
Windows
where python
macOS and Linux
which python
The path should include the environment directory.
Typical Windows path:
C:\python_project\.venv\Scripts\python.exe
Typical macOS or Linux path:
/path/to/python_project/.venv/bin/python
Verify from Python Code
import sys
print("Python executable:", sys.executable)
print("Environment prefix:", sys.prefix)
print("Base Python prefix:", sys.base_prefix)
print("Running in virtual environment:", sys.prefix != sys.base_prefix)
When running from a standard virtual environment, sys.prefix differs from sys.base_prefix.
11. Installing Packages Inside a Virtual Environment
Once the environment is activated, use pip to install project dependencies.
Example: Install requests
python -m pip install requests
Using python -m pip helps ensure that pip runs through the Python interpreter currently selected by the terminal.
Check the Installed Package
python -m pip show requests
List Installed Packages
python -m pip list
Packages installed this way are placed in the active environment by default. If the environment is not activated, use its Python executable directly or activate it before installing packages.
12. Running a Python Program in the Virtual Environment
After installing the required packages, create a Python file in your project directory.
Example: app.py
import requests
response = requests.get("https://example.com", timeout=10)
print("Status code:", response.status_code)
print("Response received successfully.")
Run the program while the virtual environment is active:
python app.py
The request requires an internet connection. The example demonstrates package usage; network failures or website restrictions can affect the actual output.
13. Deactivating a Virtual Environment
When you finish working in an environment, run:
deactivate
This removes the virtual environment's activation settings from the current shell. It does not delete the environment or uninstall its packages.
After deactivation, the terminal returns to its previous Python command configuration.
14. Reactivating an Existing Virtual Environment
You do not need to recreate a virtual environment every time you start working on a project. If it already exists, activate it again using the appropriate command.
| Operating System or Shell |
Activation Command |
| Windows Command Prompt |
.venv\Scripts\activate.bat |
| Windows PowerShell |
.\.venv\Scripts\Activate.ps1 |
| macOS/Linux Bash or Zsh |
source .venv/bin/activate |
If the terminal is closed, activation normally does not persist into a new terminal session. Simply activate the existing environment again.
15. Managing Dependencies with requirements.txt
A requirements.txt file lists Python packages required by a project. It can include exact package versions to help recreate a consistent environment.
15.1 Save Installed Packages
With the correct virtual environment activated, run:
python -m pip freeze > requirements.txt
This writes the installed distributions and versions visible to that environment into requirements.txt.
15.2 Example requirements.txt
requests==2.32.3
The version above is an illustrative example, not a guarantee that it is the newest version. Use versions appropriate for your project and verify compatibility.
15.3 Install Dependencies from a File
In a newly created and activated environment, run:
python -m pip install -r requirements.txt
This installs the listed packages and their dependencies. A requirements file generated with pip freeze may include development tools or transitive dependencies as well as direct project dependencies.
16. Creating a Fresh Environment and Installing Dependencies
A common workflow is to create an environment from scratch and then install the project's dependencies.
Windows
py -m venv .venv
.venv\Scripts\activate
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
macOS and Linux
python3 -m venv .venv
source .venv/bin/activate
python -m pip install --upgrade pip
python -m pip install -r requirements.txt
Run these commands from the project directory. If no requirements file exists yet, create one after installing the required packages or install the necessary packages individually.
17. Understanding the Virtual Environment Directory
The virtual environment directory contains the configuration and files needed to use the environment.
| Item |
Purpose |
pyvenv.cfg |
Stores configuration details, including information about the base Python installation. |
Scripts/ on Windows |
Contains the environment's executable files and activation scripts. |
bin/ on macOS/Linux |
Contains the environment's Python executable and activation scripts. |
Lib/site-packages/ on Windows |
Common location for installed third-party packages. |
lib/pythonX.Y/site-packages/ on macOS/Linux |
Common location for installed third-party packages. |
Exact paths can vary by platform and Python version. Avoid manually modifying the environment's internal files unless you understand the implications.
18. Using Virtual Environments with an IDE
Integrated development environments such as Visual Studio Code and PyCharm can use a project's virtual environment as its Python interpreter.
General Workflow
- Open the project folder in the IDE.
- Create the environment in the project directory using
python -m venv .venv or the IDE's environment tools.
- Select the interpreter located inside the
.venv directory.
- Install dependencies using the IDE's terminal or package tools.
- Run and debug your Python files using the selected interpreter.
If the editor reports that a package is missing even though it was installed, verify that the editor and terminal are using the same interpreter.
19. Virtual Environments and Version Control
A virtual environment contains generated files and installed packages that can usually be recreated. It should not normally be committed to Git or copied between different machines.
Example .gitignore
.venv/
venv/
__pycache__/
*.py[cod]
.env
The .env entry is appropriate when the project uses environment-variable files that should not be committed, especially if they contain secrets. Adjust the ignore rules according to your project's needs.
Commit your application code and dependency specification, such as requirements.txt, rather than the entire virtual environment.
20. Creating and Using a Virtual Environment with a Specific Python Version
If multiple Python versions are installed, choose the interpreter that should create the environment.
Windows Example
py -3.12 -m venv .venv
macOS/Linux Example
python3.12 -m venv .venv
These commands work only if the specified Python version is installed and accessible through the relevant launcher or command. A virtual environment uses the Python version selected when it is created; it does not automatically switch to a different Python version when activated.
21. Common Virtual Environment Errors and Solutions
| Problem |
Possible Cause |
Solution |
python is not recognized |
Python is not installed or is not on PATH. |
Install Python or correct the PATH configuration; on Windows, try py. |
No module named venv |
The Python installation lacks the required venv component. |
Check the installation and install the operating system's relevant Python venv component if required. |
| Activation script not found |
The environment was not created at that path or has a different name. |
Check the current directory and confirm that .venv exists. |
| PowerShell script execution error |
PowerShell execution policy prevents running the activation script. |
Review the applicable PowerShell policy and organizational security rules; use an approved shell or activation method. |
| Package is not found after installation |
Package was installed using a different Python interpreter. |
Activate the intended environment and use python -m pip install package_name. |
| Wrong Python version |
Environment was created using another interpreter. |
Recreate the environment using the required Python executable. |
| Environment stops working after moving the folder |
Virtual environments may contain location-dependent paths. |
Recreate the environment in the new location and reinstall its dependencies. |
| Global package appears unavailable |
Virtual environments are isolated by default. |
Install the package into the active environment instead of relying on a global installation. |
22. Troubleshooting PowerShell Activation
On some Windows systems, PowerShell may block the activation script because of the configured execution policy.
First, verify that the environment exists and that you are using the correct command:
.\.venv\Scripts\Activate.ps1
If execution is blocked, follow your organization's security guidance and the official PowerShell documentation. Do not weaken system-wide security settings just to activate a virtual environment. Alternatives include using Command Prompt or invoking the environment's Python executable directly.
23. Running Python Without Activating the Environment
Activation is convenient but not strictly required. You can call the environment's Python executable directly.
Windows
.venv\Scripts\python.exe app.py
macOS and Linux
.venv/bin/python app.py
To install a package without activating the environment, use the same executable:
Windows
.venv\Scripts\python.exe -m pip install requests
macOS and Linux
.venv/bin/python -m pip install requests
This method can be useful in automated scripts, IDE configurations, and situations where activation is unavailable.
24. Useful venv Options
The venv command supports options for creating or updating environments in different ways.
| Option |
Purpose |
--help |
Displays available command options. |
--clear |
Removes the existing contents of the target environment directory before creating the environment. |
--upgrade |
Upgrades the environment directory to use the Python installation running the command. |
--system-site-packages |
Allows the environment to access packages installed in the base Python environment. |
--without-pip |
Creates the environment without bootstrapping pip. |
--upgrade-deps |
Requests upgrades of core packaging dependencies supported by the Python version, such as pip. |
Example:
python -m venv --help
Use options such as --clear carefully because they can remove files inside the target environment directory. Keep project source files outside the virtual environment directory.
25. Practical Mini-Project: Set Up a Flask Application
Objective: Create an isolated Python environment, install Flask, and run a small web application.
Step 1: Create a Project Folder
mkdir flask_project
cd flask_project
Step 2: Create a Virtual Environment
Windows:
py -m venv .venv
macOS/Linux:
python3 -m venv .venv
Step 3: Activate the Environment
Windows Command Prompt:
.venv\Scripts\activate.bat
Windows PowerShell:
.\.venv\Scripts\Activate.ps1
macOS/Linux:
source .venv/bin/activate
Step 4: Install Flask
python -m pip install Flask
Step 5: Create app.py
from flask import Flask
app = Flask(__name__)
@app.route("/")
def home():
return "Hello from my virtual environment!"
if __name__ == "__main__":
app.run(debug=True)
Step 6: Run the Application
python app.py
Open the local address shown in the terminal in your browser. The default Flask development server commonly uses http://127.0.0.1:5000/.
Development note: Debug mode is suitable for local development, but should not be enabled for a public production deployment.
Step 7: Save the Dependencies
python -m pip freeze > requirements.txt
Step 8: Deactivate the Environment
deactivate
This project demonstrates a complete basic workflow: create, activate, install, run, record dependencies, and deactivate.
26. Best Practices for Virtual Environments
- Create a separate virtual environment for each Python project.
- Use a consistent name such as
.venv to make the environment easy to identify.
- Use
python -m pip instead of relying on an ambiguous pip command.
- Verify the active interpreter before installing dependencies.
- Keep project source code outside the virtual environment directory.
- Record dependencies in a requirements file or another suitable dependency-management format.
- Exclude virtual environment directories from version control.
- Recreate environments rather than copying them between different locations or machines.
- Use the intended Python version when creating an environment.
- Avoid installing project dependencies globally unless there is a specific reason.
- Keep development dependencies and production dependencies organized appropriately.
- Do not treat a virtual environment as a security boundary for untrusted code.
27. Practice Exercises
- Check your Python version using the terminal.
- Create a project directory named
calculator_project.
- Create a virtual environment called
.venv.
- Activate and deactivate the environment using your operating system's commands.
- Verify the interpreter path using
where python or which python.
- Install the
requests package inside the virtual environment.
- Display installed packages using
python -m pip list.
- Save installed packages to
requirements.txt.
- Create a fresh environment and install packages from that requirements file.
- Investigate what happens when you attempt to import a package that is installed globally but not in your isolated environment.
- Configure a Python IDE to use the project's virtual environment.
- Add the virtual environment directory to a Git ignore file.
28. Interview Questions and Answers
Q1. What is a virtual environment in Python?
A virtual environment is an isolated Python environment with its own package installation location and environment-specific executables. It allows different projects to manage dependencies independently.
Q2. What is venv?
venv is a Python standard library module used to create virtual environments.
Q3. How do you create a virtual environment?
Run python -m venv .venv from the project directory, using the desired Python interpreter.
Q4. How do you activate a virtual environment on Windows?
For Command Prompt, use .venv\Scripts\activate.bat. For PowerShell, use .\.venv\Scripts\Activate.ps1.
Q5. How do you activate a virtual environment on macOS or Linux?
Run source .venv/bin/activate in a compatible shell such as Bash or Zsh.
Q6. What does the deactivate command do?
It removes the environment's activation settings from the current shell. It does not delete the environment or uninstall its packages.
Q7. Why should each project have its own virtual environment?
Separate environments help prevent dependency conflicts and allow projects to use different versions of libraries.
Q8. What is requirements.txt?
It is a text file commonly used to list Python packages and versions required by a project. Packages can be installed from it using python -m pip install -r requirements.txt.
Q9. How can you check which Python interpreter is being used?
Use where python on Windows or which python on macOS/Linux. In Python code, inspect sys.executable.
Q10. Should a virtual environment be committed to Git?
Usually not. The environment can be recreated from a Python installation and dependency specification, so the environment directory is generally excluded from version control.
Q11. Can you use a virtual environment without activating it?
Yes. Run the environment's Python executable directly, such as .venv/bin/python on macOS/Linux or .venv\Scripts\python.exe on Windows.
Q12. What causes a package import error inside a virtual environment?
The package may not be installed in that environment, or the program may be running under another Python interpreter. Verify the interpreter and install the dependency using that interpreter's pip.
29. Quick Revision Checklist
- Understand the purpose of virtual environments.
- Know how to create an environment using
python -m venv .venv.
- Remember the activation commands for Windows, macOS, and Linux.
- Verify the active interpreter before installing packages.
- Use
python -m pip for package management.
- Know how to deactivate and reactivate an environment.
- Use
requirements.txt to record and install dependencies.
- Exclude the virtual environment directory from version control.
- Understand common activation, interpreter, and package installation errors.
- Practice the complete setup workflow with a small application.
30. Conclusion
Creating and activating virtual environments with venv is an essential Python development skill. Virtual environments help keep dependencies isolated, reduce package conflicts, and make project setup more manageable. By creating an environment for each project, installing packages through the correct interpreter, maintaining dependency files, and following consistent development practices, you can build cleaner and more reproducible Python applications.
Additional Learning Resources