Apps Artificial Intelligence CSS DevOps Go JavaScript Laravel Linux MongoDB MySQL PHP Python Rust Svelte Vue

Using `venv` in Python

1 min read .
Using `venv` in Python

A Python virtual environment isolates a project’s installed packages from the system Python environment and from other projects. This helps prevent dependency conflicts and makes development environments easier to reproduce.

Create a Virtual Environment

From the project directory:

python3 -m venv .venv

.venv is a common directory name because many editors recognize it automatically. You can use another name if your project has a different convention.

On some Debian or Ubuntu installations, the venv support package may need to be installed separately:

sudo apt install python3-venv

Activate It on Linux or macOS

source .venv/bin/activate

Your shell prompt often changes to show that the environment is active.

Activate It on Windows

PowerShell:

.\.venv\Scripts\Activate.ps1

Command Prompt:

.venv\Scripts\activate.bat

Activation is convenient, but not technically required. You can always invoke the environment’s Python executable directly.

Install Packages

After activation:

python -m pip install requests

Using python -m pip makes it explicit that pip belongs to the active Python interpreter.

Check installed packages:

python -m pip list

Record Dependencies

For simple projects using a requirements.txt workflow:

python -m pip freeze > requirements.txt

Another environment can install them with:

python -m pip install -r requirements.txt

For libraries and modern applications, dependency metadata is often maintained in pyproject.toml by tools such as pip, uv, Poetry, or PDM. A virtual environment remains useful regardless of which dependency-management tool creates or manages it.

Deactivate the Environment

deactivate

This restores the shell’s previous Python path.

Do Not Commit the Environment Directory

Add the environment directory to .gitignore:

.venv/

Commit dependency declarations such as pyproject.toml, lock files where appropriate, or requirements.txt instead of committing installed package files.

Recreate an Environment

Virtual environments are disposable. If one becomes inconsistent, remove it and recreate it from declared dependencies:

rm -rf .venv
python3 -m venv .venv
source .venv/bin/activate
python -m pip install -r requirements.txt

Only run destructive commands such as rm -rf after confirming that the path is correct.

Conclusion

Use one virtual environment per Python project unless your tooling has a specific reason to do otherwise. Keep the environment directory out of version control and make dependency declarations the reproducible source of truth.

Related Posts

chevron-up