How to Create a Virtual Environment in Python

Reading Time: < 1 Minute
Publication date:

A virtual environment in Python is a tool that separates project dependencies from the global environment and prevents potential conflicts between libraries. In this article, we will discuss how to create and use virtual environments in Python.

Installation and Creation of a Virtual Environment

In Python 3.3 and later versions, there is a built-in venv module to create virtual environments. To create a virtual environment, follow these steps:

  1. Open a terminal or command prompt.
  2. Navigate to the directory where you want to create the virtual environment.
  3. Enter the following command:
   python3 -m venv myenv

Here, myenv is the name of your virtual environment. You can choose any name you prefer.

Executing this command will create a folder named myenv, which will contain all the necessary files for the virtual environment.

Activating the Virtual Environment

To activate the virtual environment, use the following commands:

Windows:

myenv\Scripts\activate

macOS and Linux:

source myenv/bin/activate

After activating the environment, your terminal or command prompt will be modified, and you will see the name of the virtual environment at the beginning of the command line.

Example:

(myenv) user@host:~$

Now you are ready to work in an isolated environment!

Installing Packages and Dependencies

To install packages in the active virtual environment, use the pip install command.

Example:

(myenv) user@host:~$ pip install requests

This command will install the requests package only in the current virtual environment.

Deactivating the Virtual Environment

To exit the virtual environment and return to the global Python environment, enter the following command:

deactivate

Now you know how to create, activate, use, and deactivate a Python virtual environment!

5 / 5. 1

Share:

Leave a comment