Python venv: A Quick Start Guide
/ November 04, 2024
Getting Started with venv
What is venv?
venv is a Python module that allows you to create isolated Python environments. This is useful for managing dependencies for different projects without interfering with each other or your system-wide Python installation.
Creating a Virtual Environment
- Open your terminal or command prompt.
- Navigate to your project directory.
- Create a virtual environment:
Replacepython -m venv my_envmy_envwith your desired environment name.
Activating the Virtual Environment
On Windows:
my_env\Scripts\activate
On macOS/Linux:
source my_env/bin/activate
Once activated, your terminal prompt will change to indicate the active environment.
Installing Packages
You can now install packages within your virtual environment using pip:
pip install package_name
Deactivating the Virtual Environment
To deactivate the environment:
deactivate
Best Practices:
- Create a virtual environment for each project.
- Activate the appropriate environment before working on a project.
- Keep your virtual environments organised.
- Consider using a virtual environment manager like
virtualenvwrapperorpoetryfor more advanced features.
Example:
Let's say you have two projects: project_A and project_B.
-
Create a virtual environment for
project_A:python -m venv env_A -
Activate the environment and install required packages:
source env_A/bin/activate pip install numpy pandas matplotlib -
Create a virtual environment for
project_B:python -m venv env_B -
Activate the environment and install required packages:
source env_B/bin/activate pip install flask sqlalchemy
Now, you can work on both projects without worrying about dependency conflicts.