⚡ TechVani: AI, Technology, Apps, Coding & Digital World
TechVaniAI • Technology • Apps • Coding • Digital World
HomeAI & TechAppsCodingFree AI ToolsStudent TechSecurityAboutContactPrivacy
TECHVANI // LEARN. BUILD. TEST.

Learn the tech. Build the idea.

Clear study notes, tested lab files and practical guides for coding, AI and digital safety.

Explore Latest →
šŸ¤– AI & TechAI news, tools & guides šŸ“± Apps & ToolsUseful apps & websites šŸ’» CodingProgramming & web development šŸŽ“ Student TechStudy & career technology šŸ” Cyber SecuritySafety & awareness

Latest Posts

Circuit Notebook theme

Exam Notes

šŸ“š BTech CSE Exam Notes

Find Semester 1-8 subjects in one place. Choose a semester and open the notes you need. This is a general study guide, not an official syllabus.

Open Exam Notes →🧪 Open Lab Files →

Exam Numericals & Study Series

Practice CPU scheduling and explore OS and DBMS topics in separate, easy-to-follow parts. New topics will appear in the hub as they are published.

Open Numericals Hub →

Start here and stay in touch

New to TechVani? Start with our free AI tools guide for students. It covers which tools to try and what to check before relying on an answer.

For step-by-step videos, visit SiteSudhar on YouTube.

Join TechVani on WhatsApp

Get new AI tools and coding guides in your WhatsApp Updates tab.

Browse Topics

Popular Posts

TechVani

Python Virtual Environments for Students: venv, pip and requirements.txt

Two Python projects may need different versions of the same library. A virtual environment keeps each project's installed packages separate. This guide walks through a small project, shows how to check which Python is active, and fixes common setup errors. It is a project setup guide, not a substitute for your college's lab instructions.

1. Create a project and environment

Install Python first. Open a terminal inside your project folder. The Python Packaging User Guide recommends keeping the environment in a local .venv folder and excluding that folder from version control.

# macOS or Linux
mkdir my-python-project
cd my-python-project
python3 -m venv .venv

# Windows (PowerShell or Command Prompt)
mkdir my-python-project
cd my-python-project
py -m venv .venv

The last command makes an isolated Python installation under .venv. It does not install your project's third-party packages yet. If python3 or py is not found, check your Python installation and terminal PATH before retrying.

2. Activate and check the environment

# macOS or Linux
source .venv/bin/activate
which python

# Windows PowerShell
.venv\Scripts\Activate.ps1
where.exe python

# Windows Command Prompt
.venv\Scripts\activate.bat
where python

The interpreter path should include .venv. You may also see (.venv) in your prompt, but check the interpreter path rather than relying only on the prompt. On PowerShell, if script execution is blocked, consult your organization's policy or use Command Prompt and activate.bat. Do not change system-wide execution policy just to follow a tutorial.

3. Install and use packages

With the environment active, use python -m pip so the pip command runs with that Python interpreter.

python -m pip --version
python -m pip install requests
python -c "import requests; print(requests.__version__)"

For a project with dependencies listed in requirements.txt, install them with python -m pip install -r requirements.txt. If you installed a package but still get ModuleNotFoundError, compare the Python path from step 2 with the interpreter in your editor or notebook. They must refer to the same environment.

4. Share dependencies, not your whole environment

A quick way to record the packages installed in this environment is:

python -m pip freeze > requirements.txt

Review the generated file before sharing it: it includes every installed package in the environment, even ones you no longer use. Add .venv/ to your .gitignore instead of committing the environment directory. Another student can create their own environment and install your reviewed requirements file.

5. Leave the environment

deactivate

Next time you work on the project, activate its environment again. If you switch to another project, use that project's environment instead of installing its packages globally.

Quick practice

  1. Create two separate project folders and an environment in each.
  2. Activate the first and check the interpreter path; then deactivate it.
  3. Activate the second and check its path. Explain why each path points to a different .venv.

If you are revising basic Python syntax first, use the Python Exam Notes. For runnable exercises, see the Python Programming Lab File. The semester-wise notes hub helps you find other subjects.

References

Which Python setup problem should we explain next? Ask your questions in the comments below.

Fix common virtual environment problems

These are the errors students meet most often. I checked the basic steps by creating a real environment: after python -m venv .venv, the interpreter inside it reports a different prefix from the system Python, which proves the environment is isolated.

  • "Activate.ps1 cannot be loaded" on Windows PowerShell. Execution policy can block scripts. Use the environment interpreter directly or follow your organization's policy; do not change system-wide policy just for this guide.
  • pip installs into the wrong Python. Run python -m pip install package instead of pip install package. This uses the pip that belongs to the Python you are running.
  • Your editor still shows import errors. The editor is using a different interpreter. Select the interpreter inside .venv in your editor settings.
  • You moved or renamed the project folder. Environment scripts can contain absolute paths. Verify the environment folder, preserve your project code and dependency record, then recreate only the environment; do not delete the project itself.
  • You committed .venv to Git. Add .venv/ to .gitignore. Share requirements.txt instead.

Which command do I use?

TaskmacOS / LinuxWindows
Createpython3 -m venv .venvpy -m venv .venv
Activatesource .venv/bin/activatecmd: .venv\Scripts\activate.bat; PowerShell: .venv\Scripts\Activate.ps1
Save packagespython -m pip freeze > requirements.txtpython -m pip freeze > requirements.txt
Leavedeactivatedeactivate

Check yourself

Q1. You run pip install requests but the import still fails inside your active environment. What is the first thing to try?

Answer: run python -m pip install requests, then python -c "import requests". It makes sure the package goes into the same Python you run.

Q2. Why should .venv not be uploaded to GitHub?

Answer: it is large, it is specific to your computer, and it can be rebuilt from requirements.txt.

Related reading on this blog: tested lab files and the Exam Numericals Hub.

Which Python owns the packages?

Base Python → creates two environments
Project A → .venv-a/bin/python → A site-packages
Project B → .venv-b/bin/python → B site-packages
python -m pip → pip for that chosen Python
Activation → changes this shell's PATH convenience
Editor / notebook → must select the same interpreter

A venv separates installed Python packages by default. It is not a container, a new operating system, or a security sandbox: untrusted Python code can still access your files/network with your normal permissions. --system-site-packages deliberately exposes base-system packages, so leave it off for this beginner lab.

Activation is optional: use the exact interpreter

# Linux / macOS
.venv/bin/python -c "import sys; print(sys.executable); print(sys.prefix != sys.base_prefix)"
.venv/bin/python -m pip --version

# Windows PowerShell / cmd
.venv\Scripts\python.exe -c "import sys; print(sys.executable); print(sys.prefix != sys.base_prefix)"
.venv\Scripts\python.exe -m pip --version

True for sys.prefix != sys.base_prefix confirms this interpreter is running in a virtual environment. An activation prompt or VIRTUAL_ENV variable is not enough. Use this direct route when activation scripts are blocked; changing a system policy is unnecessary.

Offline lab: prove package separation and replay requirements

The following Linux/macOS shell lab was executed on Python 3.10.12. Run it only in a new empty disposable project folder. It creates two environments and a tiny local wheel containing one module, with no network package download. This wheel is a controlled teaching fixture, not packaging guidance for shipping a real project. Keep the local files until the experiment ends.

# Linux/macOS lab. Run in a NEW, disposable, empty project folder.
# No network download; installs a tiny local module only inside these environments.
set -eu
python3 -m venv .venv-a
python3 -m venv .venv-b
.venv-a/bin/python - <<'PY'
import sys, zipfile
assert sys.prefix != sys.base_prefix
print('A isolated:', sys.prefix != sys.base_prefix)
# Build a minimal local wheel, without a build service or a public package.
files = {
 'tv_demo.py': 'VALUE = 7\n',
 'tv_demo-1.0.dist-info/METADATA': 'Metadata-Version: 2.1\nName: tv-demo\nVersion: 1.0\n',
 'tv_demo-1.0.dist-info/WHEEL': 'Wheel-Version: 1.0\nGenerator: local-demo\nRoot-Is-Purelib: true\nTag: py3-none-any\n',
}
files['tv_demo-1.0.dist-info/RECORD'] = ''.join(name + ',,\n' for name in files) + 'tv_demo-1.0.dist-info/RECORD,,\n'
with zipfile.ZipFile('tv_demo-1.0-py3-none-any.whl', 'w') as wheel:
    for name, body in files.items(): wheel.writestr(name, body)
PY
.venv-a/bin/python -m pip install --no-index ./tv_demo-1.0-py3-none-any.whl >/dev/null
.venv-a/bin/python - <<'PY'
import tv_demo
print('A module value:', tv_demo.VALUE)
assert tv_demo.VALUE == 7
PY
.venv-b/bin/python - <<'PY'
import importlib.util, sys
print('B isolated:', sys.prefix != sys.base_prefix)
print('B has module:', importlib.util.find_spec('tv_demo') is not None)
assert sys.prefix != sys.base_prefix
assert importlib.util.find_spec('tv_demo') is None
PY
# Exclude pip itself by filtering for this demo's reviewed dependency.
.venv-a/bin/python -m pip freeze | grep '^tv-demo' > requirements.txt
.venv-a/bin/python - <<'PY'
from pathlib import Path
text = Path('requirements.txt').read_text()
print('requirements has local wheel:', 'tv-demo @ file:' in text)
assert 'tv-demo @ file:' in text
PY
.venv-b/bin/python -m pip install --no-index -r requirements.txt >/dev/null
.venv-b/bin/python - <<'PY'
import tv_demo
print('B after requirements:', tv_demo.VALUE)
assert tv_demo.VALUE == 7
PY

Checked output (pip progress is hidden by the script):

A isolated: True
A module value: 7
B isolated: True
B has module: False
requirements has local wheel: True
B after requirements: 7

B cannot find tv_demo until its own interpreter installs it. The frozen entry is a local file reference, not a portable package-index pin. It works for B here because the wheel stays at that absolute path on the same machine. Before sharing requirements, replace machine-specific paths with an intentional distributable source and review each dependency.

Requirements are a snapshot, not a universal lock

  • pip freeze records installed distributions; it does not solve dependencies or generate a universal lockfile.
  • Record the Python version and intended OS too. A requirements file alone does not guarantee the same result on every machine.
  • Review unused packages, local paths and private index references before sharing. Do not commit credentials.
  • Keep .venv/ out of Git. Also ignore the demo's .venv-a/ and .venv-b/ if you keep this experiment.
  • Recreate a venv after moving it or changing its base Python. Do not assume copying its directory is portable.

Diagnose setup errors in order

  1. Print sys.executable from the program or notebook that fails, not just from a different terminal.
  2. Run that interpreter with -m pip --version to see which pip/site-packages it owns.
  3. Check package spelling and reviewed requirements. An import name can differ from its distribution name.
  4. If the interpreter is wrong, select the correct one in the editor/notebook before reinstalling.
  5. If venv creation reports missing ensurepip, use the official Python/OS setup guidance or your lab administrator. Do not patch it by installing random scripts or using sudo pip.

Exam and interview quick answers

  1. Do you have to activate? No. Call the environment's Python by its path.
  2. Why python -m pip? It binds pip to that Python interpreter.
  3. Does a prompt prove the editor uses the same Python? No. Print sys.executable in the failing program.
  4. Does venv isolate system access? No. Package isolation is not a security sandbox.
  5. Does deactivate delete the venv? No. It only changes the current shell state.
  6. Can you move/copy a venv reliably? Not generally. Recreate it from reviewed dependency information.
  7. Is pip freeze a lockfile? No. It reports installed packages, not a new dependency solution.
  8. Why can a requirement work locally but fail for a friend? It may contain a machine-specific file path or require a different platform/Python version.

Grounding: Python venv documentation, Packaging User Guide, and pip freeze. Windows commands are documentation-grounded; the executed offline lab was on Linux, not Windows.

Comments