How to Use Virtual Environment on Raspberry Pi Easily
On Raspberry Pi, you can use
python3 -m venv myenv to create a virtual environment named myenv. Activate it with source myenv/bin/activate to isolate your Python packages from the system.Syntax
To create a virtual environment, use the command:
python3 -m venv <env_name>: Creates a new virtual environment folder named<env_name>.source <env_name>/bin/activate: Activates the virtual environment so Python uses its packages.deactivate: Exits the virtual environment and returns to the system Python.
bash
python3 -m venv myenv source myenv/bin/activate # work inside virtual environment deactivate
Example
This example shows how to create a virtual environment called myenv, activate it, install a package, and then deactivate it.
bash
python3 -m venv myenv
source myenv/bin/activate
pip install requests
python3 -c "import requests; print(requests.__version__)"
deactivateOutput
2.31.0
Common Pitfalls
Common mistakes include:
- Not activating the virtual environment before installing packages, which installs them globally.
- Using
pythoninstead ofpython3if Python 3 is not the default. - Trying to activate the environment with Windows commands on Raspberry Pi (Linux).
bash
## Wrong: Installing without activating pip install flask ## Right: Activate first source myenv/bin/activate pip install flask
Quick Reference
Remember these quick commands:
python3 -m venv env_name: Create environmentsource env_name/bin/activate: Activate environmentdeactivate: Exit environmentpip install package: Install packages inside environment
Key Takeaways
Always activate your virtual environment before installing packages to keep them isolated.
Use
python3 explicitly on Raspberry Pi to avoid version confusion.Deactivate the environment when done to return to the system Python.
Virtual environments help keep projects clean and prevent package conflicts.