Photo by Cathryn Lavery on Unsplash
Activity #18: Research Virtual Environment and Python package manager
How to Create and Use Virtual Environments
Create Folder and type CMD in search bar
Create a Virtual Environment: In CMD, run the following command in your terminal to create a virtual environment:
python -m venv venv
This creates a folder (
venv
) containing a Python interpreter and a separate package directory.Activate the Virtual Environment:
venv\Scripts\activate
After activation, your terminal prompt changes, indicating the virtual environment is active.
- Install Dependencies: Install packages using pip, and they’ll only be available in this environment:
pip install package_name
- Deactivate the Environment: When done, simply deactivate it by typing:
Deactivate
Best Practices: Managing Dependencies
To ensure that your virtual environment is not uploaded to GitHub or other cloud repositories, follow these steps:
Use .gitignore to Exclude the Virtual Environment: Create or edit a .gitignore
file in your project root and add the following line:
venv/
This prevents Git from tracking your venv
folder, keeping your repository clean.
Generate a requirements.txt
file: To save all dependencies, run:
(Make sure the Virtual Environment is activated.)
pip freeze > requirements.txt
This file lists all installed packages with their versions.