Creating and Managing Virtual Environments
Creating a Virtual Environment
In this section, we'll demonstrate how to create a Python virtual environment using the built-in venv
module.
- Open a terminal on your Ubuntu 22.04 system.
- Ensure that you have Python 3 installed by running the following command:
python3 --version
- Create a new virtual environment by running the following command:
python3 -m venv my_project_env
This will create a new virtual environment named my_project_env
in the current directory.
Activating and Deactivating the Virtual Environment
To use the virtual environment, you need to activate it. Run the following command to activate the virtual environment:
source my_project_env/bin/activate
You should see the name of the virtual environment (my_project_env)
prepended to your terminal prompt, indicating that the virtual environment is now active.
To deactivate the virtual environment, simply run the following command:
deactivate
This will return you to the system's default Python environment.
Managing Dependencies in the Virtual Environment
Once the virtual environment is active, you can install Python packages and their dependencies using the pip
package installer. For example, to install the numpy
library, run the following command:
pip install numpy
You can also create a requirements.txt
file to capture the exact versions of the packages used in your project, and then install them using the following command:
pip install -r requirements.txt
This ensures that the same set of dependencies can be easily installed on other machines or in different environments, promoting reproducibility.
Removing a Virtual Environment
If you no longer need a virtual environment, you can remove it by simply deleting the directory where it was created. For example:
rm -rf my_project_env
This will permanently delete the virtual environment and all the packages installed within it.