Python virtual environments are a great way to manage dependencies for your projects. They allow you to create isolated environments where you can install packages specific to a project without affecting your system-wide Python installation. This blog post will guide you through setting up a Python virtual environment using venv.
Step-by-Step Guide
Install Python
First, ensure that Python is installed on your system. Most modern Linux distributions, including Ubuntu, come with Python pre-installed. You can check if Python is installed by running:
If Python is not installed, you can install it using:
sudo apt install python3
Install python3-venv
To create a virtual environment, you need the python3-venv package. Install it using:
sudo apt install python3-venv
Create a Virtual Environment
Choose a directory where you want to store your project and navigate to it. Then create a virtual environment using the following command:
Here, myenv is the name of the virtual environment. You can name it anything you like.
Activate the Virtual Environment
To start using the virtual environment, you need to activate it. Run the following command:
Install Packages
With the virtual environment activated, you can now install Python packages using pip. For example, to install the requests library, run:
The installed packages will be specific to this virtual environment.
Deactivate the Virtual Environment
When you are done working in the virtual environment, you can deactivate it by running:
This will return you to the system’s default Python environment.
Reactivate the Virtual Environment
Whenever you want to work on your project again, navigate to your project directory and activate the virtual environment:
Note: This guide is written for Linux/Ubuntu systems. The commands may vary slightly for other operating systems.