DEV Community

Cover image for Setting Up a Python Virtual Environment (venv)
Zobaidul Kazi
Zobaidul Kazi

Posted on • Updated on

Setting Up a Python Virtual Environment (venv)

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

  1. 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:

python3 --version
Enter fullscreen mode Exit fullscreen mode

If Python is not installed, you can install it using:

sudo apt update
sudo apt install python3
Enter fullscreen mode Exit fullscreen mode
  1. Install python3-venv

To create a virtual environment, you need the python3-venv package. Install it using:

mkdir myproject
cd myproject
Enter fullscreen mode Exit fullscreen mode
  1. 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:

python3 -m venv .venv
Enter fullscreen mode Exit fullscreen mode

Here, myenv is the name of the virtual environment. You can name it anything you like.

  1. Activate the Virtual Environment

To start using the virtual environment, you need to activate it. Run the following command:

source .venv/bin/activate
Enter fullscreen mode Exit fullscreen mode
  1. Install Packages

With the virtual environment activated, you can now install Python packages using pip. For example, to install the requests library, run:

pip install fastapi
Enter fullscreen mode Exit fullscreen mode

The installed packages will be specific to this virtual environment.

  1. Deactivate the Virtual Environment

When you are done working in the virtual environment, you can deactivate it by running:

deactivate
Enter fullscreen mode Exit fullscreen mode

This will return you to the system's default Python environment.

  1. Reactivate the Virtual Environment

Whenever you want to work on your project again, navigate to your project directory and activate the virtual environment:

source myenv/bin/activate
Enter fullscreen mode Exit fullscreen mode

Note: This guide is written for Linux/Ubuntu systems. The commands may vary slightly for other operating systems.

Top comments (0)