Python Tutorial / Create Virtual Environments and Manage Packages with pip
A virtual environment separates a project’s installed Python packages from those of other projects. Run pip as python -m pip to make the interpreter receiving the installation explicit.
Understand the separation
Two projects may need different versions of the same package. Updating one shared installation can break an unrelated project, so create a .venv directory for each project. A virtual environment separates package installations; it does not isolate file access or operating-system permissions. Code still runs with your user’s privileges.
For the relevant APIs and platform requirements, see Create Virtual Environments and Manage Packages with pip documentation.
| Item | Role |
|---|---|
| Python | Executes your code |
| venv | Creates a project environment |
| pip | Installs, inspects and removes external packages |
| requirements.txt | Records packages and versions for later installation |
Create and activate an environment
Inspect an existing .venv before recreating it. For a new project, run the following using the interpreter you intend to use:
python -m venv .venv
Activate it in Windows PowerShell:
.\.venv\Scripts\Activate.ps1
On macOS or Ubuntu, use:
source .venv/bin/activate
If PowerShell blocks activation, follow organizational policy or call .venv\Scripts\python.exe directly. You do not need to relax the execution policy for the whole computer to use a virtual environment.
Install a package and record dependencies
The example uses pandas for tabular data. Install only packages the project needs, and check the package name and official distribution source. A distribution’s installation name and its import name are not always identical.
python -m pip install pandas python -m pip show pandas python -m pip freeze > requirements.txt python -m pip install -r requirements.txt
pip freeze records the current installed environment. It does not guarantee an identical installation on every operating system or replace file-hash verification. Shell redirection can use different text encodings across PowerShell versions; check requirements.txt encoding if reinstalling from it fails.
Check the environment before reinstalling
python -c "import sys; print(sys.executable)" python -m pip --version python -m pip check
For ModuleNotFoundError, first identify the executing interpreter, then install into that environment. A global administrator installation does not correct a mismatch. Certificate and proxy failures require checking the network and trust configuration rather than disabling TLS verification.
Run deactivate when finished. Remove an unwanted package with python -m pip uninstall package-name. Before deleting and rebuilding .venv, confirm that scripts and dependency records live outside it. Keep environment rebuilding separate from deleting project data.






