A Python Virtual Environment is a self-contained directory that contains a Python interpreter and a set of packages, isolated from the system’s global Python environment.
This allows you to:
- Manage dependencies for specific projects
- Avoid version conflicts between packages
- Keep your system’s global Python environment clean and stable
1) Install venv (if you haven’t already)
venv is the standard Python package for creating virtual environments. You can install it using pip:
pip install --user venv
2) Create a new virtual environment
Choose a directory for your project and navigate to it in your terminal/command prompt. Then, run:
python -m venv myenv
Replace myenv with the name of your virtual environment.
3) Activate the virtual environment
To activate the virtual environment, run:
# On Windows
myenv\Scripts\activate
# On macOS/Linux
source myenv/bin/activate
Your command prompt should now indicate that you’re working inside the virtual environment.
4) Install packages
Now you can install packages using pip, and they’ll be isolated to this virtual environment, Example:
pip install requests
5) Deactivate the virtual environment
When you’re finished working in the virtual environment, deactivate it by running:
deactivate
That’s it! You’ve successfully set up a Python Virtual Environment.
Remember to activate the virtual environment whenever you work on your project, and deactivate it when you’re finished.