DEV Community

Cover image for Python 101: How to Create and Use Virtual Environments
John Austin Benavidez
John Austin Benavidez

Posted on

Python 101: How to Create and Use Virtual Environments

Hey there!

In this tutorial, we're going to go through the process of setting up a virtual environment in Python. But first, let's talk about what exactly a virtual environment is and why it's useful.

A virtual environment is essentially a tool that allows you to create separate Python environments on a single machine. This is really handy when you're working on multiple projects that might require different versions of packages or modules. By using virtual environments, you can isolate the dependencies for each project and ensure that they don't interfere with one another.

Okay, so now that we know what virtual environments are and why they're useful, let's get started setting one up.

To create a virtual environment, you'll need to have Python 3.3 or a later version installed. Once you have that, open up a terminal or command prompt and navigate to the directory where you want to create your virtual environment. Then, run the following command:

python3 -m venv myenv

Make sure to replace "myenv" with the desired name for your environment. This will create a directory with the specified name that contains the Python executable and other necessary files for the virtual environment.

To activate the virtual environment, run the following command:

source myenv/bin/activate

Again, be sure to replace "myenv" with the name of your virtual environment. You'll know that the virtual environment is active when you see the name of your environment in parentheses at the beginning of your terminal prompt.

To deactivate the virtual environment, simply run the deactivate command.

Once you've got your virtual environment set up and activated, you can start installing packages using pip. For example, if you wanted to install the numpy package, you would run the following command:

pip install numpy

This will install the numpy package in your virtual environment, and it will only be available for use within that environment. If you switch to a different environment or deactivate the current one, the numpy package will no longer be accessible.

So, to sum up, virtual environments are really useful for isolating dependencies and packages for different projects, making it easier to manage and share your code. They also allow you to create a reproducible environment for your project, which is especially handy when you're working with other people.

I hope this tutorial has been helpful in explaining how to set up a virtual environment in Python and the benefits of using them. Happy coding!

Top comments (0)