How do I create and use a virtual environment in Python?
Use `venv` to create a virtual environment. Activate it to manage dependencies separately for each project, keeping your global Python environment clean.
Creating and using a virtual environment in Python is essential for managing project dependencies without affecting your global Python installation. Virtual environments allow you to isolate dependencies for different projects, preventing version conflicts and ensuring reproducibility. To create a virtual environment, use the venv
module, which is included in Python's standard library:
python -m venv myenv
This command creates a directory named myenv
containing a new Python installation. To activate the virtual environment, run the appropriate command based on your operating system:
- Windows:
myenvScriptsactivate
- macOS/Linux:
source myenv/bin/activate
Once activated, you can install packages using pip
, and they will be installed only in the virtual environment:
pip install requests
To deactivate the virtual environment, simply run:
deactivate
By managing your dependencies within virtual environments, you ensure that each project remains isolated and that your global environment remains clean and stable.