Python3 Virtual Environment Fundamentals
Python Virtual Environments are a tool used to create isolated spaces on your computer where you can install and manage different versions of Python, as well as their respective packages, without affecting the global system installation. This isolation helps avoid version conflicts between projects that require different dependencies or libraries.
Here's an in-depth look at how they work:
Why Use Virtual Environments?
- Isolation: Each virtual environment is independent of others, ensuring no interference occurs between projects with conflicting requirements.
- Dependency Management: It allows you to manage dependencies for a specific project without affecting other projects or the system's Python installation.
- Reproducibility: By using virtual environments, it becomes easier to replicate your development environment on another machine or share with others.
- Safety: It prevents accidental modification of global packages and allows you to experiment without risking the system's Python installation.
Create a venv
To create a virtual environment, go to the root of your project and run
python -m venv venv
It will create a virtual environment called venv
Activate venv
./venv/bin/activate
or ./.venv/bin/activate
Verify it is working with:
which python
and it should be "something-something"/venv/bin/python
Intall packages
Depending on what you're gonna do with the project. Use pip
to install packages.
pip install jupyter matplotlib numpy pandas scipy scikit-learn
pip install Flask
pip install django
or
python -m pip install -U jupyter matplotlib numpy pandas scipy scikit-learn
Create requirements.txt
pip freeze > requirements.txt
Deactivate venv
deactivate
Install packages from requirements.txt
pip install -r requirements.txt
Place the requirements.txt
file in the root of your project directory.
When ready to install the dependencies, ensure the current working directory (CWD) is the project directory
and your virtual environment is activated. Then, run pip install -r requirements.txt
to install the listed packages within your virtual environment.
python -m venv venv
./venv/bin/activate
pip install -r requirements.txt
Also, more often lately (2023+), people have been suggesting your use .venv
(note the dot).
Besure your .gitignore
file has both venv/
and .venv/
in it.