1. Install Required Tools
Ensure python3-venv is installed (for creating virtual environments):
sudo apt updatesudo apt install python3-venv
2. Create a Virtual Environment
- Navigate to the directory where you want the virtual environment:
cd /path/to/your/project - Create a virtual environment:
python3 -m venv venv- The
venvdirectory will be created, containing a local Python installation and isolated environment.
- The
3. Activate the Virtual Environment
Activate the environment:
- For Bash/Zsh:
source venv/bin/activate - For Fish Shell:
source venv/bin/activate.fish
Once activated, your shell prompt will change to indicate you’re in the virtual environment (e.g., (venv)).
4. Upgrade pip, setuptools, and wheel
Update the essential Python tools:
pip install --upgrade pip setuptools wheel
5. Install Python Modules (e.g., distutils)
You can now install any Python modules in this isolated environment:
pip install setuptools
6. Verify Installation
Check if the required module is available:
python -c "import distutils; print('Distutils is available')"
7. Exit the Virtual Environment
To leave the virtual environment, deactivate it:
deactivate
Benefits of Using a Virtual Environment
- Isolation: Keeps dependencies separate from the system Python environment.
- Reproducibility: Ensures consistent behavior across projects.
- Safety: Prevents accidental modifications to the global Python environment.
Using a Custom Python Version
If you need a custom Python version (e.g., compiled from source), you can point venv to use it:
/path/to/custom/python3 -m venv venv
This ensures your virtual environment uses the specific Python version.
