This guide provides step-by-step instructions for creating and using Python virtual environments on Ubuntu. Virtual environments are useful for isolating Python projects and managing dependencies.
venv
Module Ensure Python is installed on your system. If not, install it using:
sudo apt update
sudo apt install python3
venv
Module Check if the venv
module is installed:
python3 -m venv --help
If not installed, install it:
sudo apt install python3-venv
Navigate to your project directory and create a virtual environment:
python3 -m venv venv_workspace
This command creates a virtual environment named venv_workspace
in your project directory.
Activate the virtual environment:
source venv_workspace/bin/activate
Your terminal prompt will change, indicating the virtual environment is active.
To deactivate the virtual environment, simply run:
deactivate
Your prompt will return to the original state.
While the virtual environment is active, use pip
to install packages:
pip install package_name
List installed packages in the virtual environment:
pip list
To use the virtual environment in a script, add the following line at the beginning of your script:
#!/path/to/venv_workspace/bin/python
This ensures the script uses the Python interpreter from the virtual environment.
Go back to Python Guide.
Visit other Developer Guides.