Python – Virtual Environment

This is a short step-by-step introduction on how to build virtual environment in Python and how to use it. Virtual envirnments keep dependencies, required by the specific project separated. Thus, it is the “clean and clear” place of the project, only with the packages that are needed and nothing else. In this article, I will use Python 3 and Windows.

Some “dirty” snow in Rila. Photo is a bit unrelated.

Installing a virtual environment:

The command for the installation:

Once installed, you may test the installation:

Creating the virtual environment:

To create the virtual environment, these are the steps:

  • Go to the folder, in which you would like to set the virtual environment

  • Write the name of the virtual environment. In this example, the name would be “my_env”:

  • Take a look at the directory named “my_env”. It should consist the following files and folders:

Activating the virtual environment:

Activating the environemnt is done with calling the file “activate”, showing the path to it:

Once the environment is activated, you see its name in parenthesis at the start. In this case it is “(my_env)”.

Deactivating the virtual environment

You can either restart the PC or simply write in the command prompt:

Installing random libraries for python:

The following would work quite ok, installing SQLAlchemy:

Making requirements.txt

Requirements.txt is a dream file. Like a magic. It goes through the environment, gets all the dependencies and collects them in one file. With one line only:

And in the folder in which we are, we get the following beautiful file, containing this line only:

SQLAlchemy==1.3.18

What can we do with it?

Installing requirements.txt to a new environment

The idea of having “requirements.txt” is that with one line, all the dependencies could be installed to the current environment:

Thank you for reading my blog.

Tagged with: , , ,