Learn how to create virtual environments in Python and use requirements.txt to install dependencies

In Python, a virtual environment is an isolated environment for running your Python programs. Using a virtual environment allows your program to have its own dependencies (different versions of packages). For example, Program A uses a specific version of packageX, while Program B uses an older version of packageX. Here is the problem visually:

If you put the two program into the same default environment, you will run into problem with packageX — if you try to install a specific version of packageX, it will override the other version.

A better solution is to create two isolated environments— aka virtual environments. Each virtual environment will then host the specific versions of packageX that each program needs, like this:

In this article, I will show you how you can create virtual environments using the conda package manager. In addition, I will also show you how you can obtain a list of packages that you have installed in your environment (through the pip command) and perform the same installation on another virtual environment using the requirements.txt file.

Conda is an open source package and environment management system that runs on Windows, Mac OS and Linux.

This article assumes that you have Anaconda (https://www.anaconda.com/products/individual-d) installed on your computer.

To create a new virtual environment, use the conda command with the following options:

conda create --name Project1 python=3.9

The above command creates a virtual environment named Project1, with the Python version set at 3.9:

Once the virtual environment is created, you can view the list of virtual environments you have on your computer using the following command:

conda info --envs

You should see something like the following:

(base) weimenglee@Wei-Mengs-Mini ~ % conda info --envs
# conda environments:
#
base * /Users/weimenglee/miniforge3
Project1 /Users/weimenglee/miniforge3/envs/Project1

With the new virtual environment created, it is time to activate it:

(base) weimenglee@Wei-Mengs-Mini ~ % conda activate Project1(Project1) weimenglee@Wei-Mengs-Mini ~ %

As you can see above, once the Project1 virtual environment is activated, you will see the name of the virtual environment (Project1) in front of the command prompt:

(Project1) weimenglee@Wei-Mengs-Mini ~ %

To know what are the packages…

Continue reading: https://towardsdatascience.com/creating-python-virtual-environments-f7bc4cbbd328?source=rss—-7f60cf5620c9—4

Source: towardsdatascience.com