Following along the book using a VSCode Dev Container
virtualenv
is another popular tool for creating isolated Python environments. While it doesn't handle dependency management like Pipenv, it’s simple, lightweight, and works well when you only need environment isolation. Here’s how to get started with virtualenv
:
First, install virtualenv
using pip
:
pip install virtualenv
Navigate to your project directory and create a virtual environment. By convention, it’s usually called venv
, but you can name it whatever you like:
virtualenv venv
This creates a venv
folder with a standalone Python environment, including a separate bin
or Scripts
directory with its own Python interpreter and pip installer.
After creating the environment, activate it:
- On macOS/Linux:
source venv/bin/activate
- On Windows:
.\venv\Scripts\activate
Once activated, you’ll see (venv)
or your environment name in the terminal prompt, indicating you’re working in the virtual environment.
After activation, any package installed with pip
is installed only within this environment:
pip install requests
You can freeze the current list of dependencies into a requirements.txt
file:
pip freeze > requirements.txt
To exit the virtual environment and return to your system Python, simply run:
deactivate
To replicate the same environment on another machine:
- Create and activate a new
virtualenv
. - Install the dependencies listed in
requirements.txt
:pip install -r requirements.txt
- Create Virtual Environment:
virtualenv venv
- Activate Environment:
source venv/bin/activate
(macOS/Linux) or.\venv\Scripts\activate
(Windows) - Deactivate Environment:
deactivate
- Install Packages:
pip install package_name
- Save Dependencies:
pip freeze > requirements.txt
- Install from Requirements:
pip install -r requirements.txt
- Pipenv handles both environment and dependency management, making it ideal for complex projects.
- Virtualenv is lightweight and fast, but requires additional tools like
pip
andrequirements.txt
to manage dependencies.
If you want environment management with simpler tooling, go with virtualenv
. If you need both environment and dependency management, Pipenv
may be more convenient.