How do I create and manage virtual environments in Python?
· Category: Python Programming
Short answer
A virtual environment is an isolated Python installation with its own packages. Use the built-in venv module (or virtualenv) to create one, then activate it to keep project dependencies separate from the system Python.
Steps
- Create a virtual environment:
python -m venv .venv. - Activate it (Windows:
.venv\Scriptsctivate, Linux/macOS:source .venv/bin/activate). - Install packages with
pip.
python -m venv .venv
.venv\Scriptsctivate
pip install requests
Tips
- Always add
.venv/orvenv/to.gitignore. - Pin dependencies with
pip freeze > requirements.txtand recreate environments withpip install -r requirements.txt. virtualenvis a third-party tool with additional features;venvis built-in and sufficient for most cases.- Use
python -m pipinstead ofpipdirectly to ensure you are using the environment's pip.
Common issues
- Forgetting to activate the environment installs packages into the system Python.
- Moving a virtual environment directory breaks absolute paths in scripts; recreate it instead.
- Conflicts between globally installed packages and virtual environment packages can cause unexpected behavior.