Managing Dependencies: Virtual Environments
As soon as you start using third-party libraries (like requests, pandas, etc.), you face the problem of dependency management. Different projects often require different versions of the same library.
A Virtual Environment (venv) is a self-contained directory that holds a specific Python interpreter and its own set of installed packages, isolated from other projects and the system-wide Python installation.
Key Commands
1. Creating the Environment
Navigate to your project folder and run:
bash python3 -m venv my_project_env
(This creates a folder named my_project_env)
2. Activating the Environment
-
Mac/Linux: bash source my_project_env/bin/activate
-
Windows (Command Prompt): bash my_project_env\Scripts\activate.bat
-
Windows (PowerShell): bash my_project_env\Scripts\Activate.ps1
Once activated, your terminal prompt will show the environment name (e.g., (my_project_env) $).
3. Installing Packages
Use pip to install packages. They will only be installed in the active environment.
bash (my_project_env) $ pip install requests
4. Deactivating
bash (my_project_env) $ deactivate