Tuesday, 15 April 2025

 

How to Set Up a Python Virtual Environment and Get Project-Specific pip list

If you're working on a Python project and want to isolate your dependencies β€” and generate a list of installed packages only for that project β€” follow this simple guide. This is especially helpful if you have .py files in a folder (like app.py, travel_engine.py) and want a clean setup.


πŸ“ Project Folder Example

Let’s say your project is located at:


C:\Users\sek\Downloads\travelbuddy\

βœ… Step 1: Open Command Prompt

  1. Press Win + R, type cmd, and press Enter.

  2. Navigate to your project folder:


cd C:\Users\sek\Downloads\travelbuddy\

βœ… Step 2: Create a Virtual Environment

python -m venv venv

This creates a venv/ folder with an isolated Python environment.


βœ… Step 3: Activate the Virtual Environment

venv\Scripts\activate

Once activated, your terminal will show the environment name like this:

(venv) C:\Users\sekha\Downloads\travelbuddy_flask-main\travelbuddy_flask-main>

βœ… Step 4: Install pipreqs (to auto-detect dependencies)

pip install pipreqs

βœ… Step 5: Generate requirements.txt

pipreqs . --force

This scans your .py files (like app.py, travel_engine.py) and writes a requirements.txt file with only the third-party libraries actually used.


βœ… Step 6: Install Required Packages

pip install -r requirements.txt

This installs everything your project needs inside the virtual environment.


βœ… Step 7: List Installed Packages (Project-Specific)

pip list

This gives you a clean list of packages installed only in this environment, not globally.


βœ… (Optional) Freeze Package Versions

If you want an exact versioned list (great for sharing or deployment):

bash

pip freeze > full_requirements.txt

🧹 Tip: To Deactivate the Virtual Environment

Just run:

bash

deactivate

🧠 Final Thoughts

Using a virtual environment keeps your project clean and avoids "dependency hell" with conflicting packages. Tools like pipreqs make it even easier by auto-generating requirements.txt from your code.

Let me know if you’d like to automate this setup even more or troubleshoot anything!