Python’s built-in venv
module allows you to create lightweight virtual environments without needing external tools like virtualenv
. It’s available in Python 3.3 and newer.
Use the python
command with the -m venv
option to create a virtual environment.
python -m venv env_name
venv
:python -m venv venv
python3.11 -m venv myenv
This ensures the virtual environment uses a specific Python version.
To start using the virtual environment, you need to activate it.
venv\Scripts\activate
source venv/bin/activate
Once activated, the terminal prompt will display the environment name, e.g., (venv)
.
To stop using the environment, deactivate it:
deactivate
This returns you to the system’s global Python environment.
To see the installed packages in your virtual environment:
pip list
Install packages using pip
:
pip install package_name
To save all installed packages to a file:
pip freeze > requirements.txt
Recreate an environment using the requirements.txt
file:
pip install -r requirements.txt
To delete a virtual environment, simply remove its directory:
rm -rf venv
Environment Naming:
my_project_env
.Project-Specific Environments:
Create the virtual environment within the project folder:
cd my_project
python -m venv venv
Add venv
to your .gitignore
file to avoid committing it to version control.
Keep Dependencies Up-to-Date:
Regularly update packages:
pip install --upgrade pip
pip list --outdated
pip install --upgrade package_name
Use requirements.txt for Reproducibility:
requirements.txt
file for team collaboration or deployment.venv
Objective: Learn to create, manage, and work with virtual environments using Python's built-in venv
module.
Create a Virtual Environment:
test_env
in the current directory.python -m venv test_env
Activate and Install Packages:
requests
library.On Windows:
test_env\Scripts\activate
On macOS/Linux:
source test_env/bin/activate
Then, install the requests
library:
pip install requests
Save Dependencies:
requirements.txt
file.pip freeze > requirements.txt
Recreate Environment:
deactivate
rm -rf test_env # On macOS/Linux
rmdir /S /Q test_env # On Windows
requirements.txt
file.python -m venv test_env
source test_env/bin/activate # On Windows: test_env\Scripts\activate
pip install -r requirements.txt
Experiment with Python Versions:
python3.9 -m venv py39_env
source py39_env/bin/activate # On Windows: py39_env\Scripts\activate
python --version