Skip to main content
p. 416

17.3 Runtime-Based Virtualization

A final kind of virtualization to mention is based on the type of environment used to develop an application. This differs from the system virtual machines and containers that we’ve seen so far, because it doesn’t use the idea of placing applications onto different machines. Instead, it’s a separation that applies only to a particular application.

The reason for these kinds of environments is that multiple applications on the same system can use the same programming language, causing potential conflicts. For example, Python is used in several places on a typical distribution and can include many add-on packages. If you want to use the system’s version of Python in your own package, you can run into trouble if you want a different version of one of the add-ons.

Let’s look at how Python’s virtual environment feature creates a version of Python with only the packages that you want. The way to start is by creating a new directory for the environment like this:

$ python3 -m venv test-venv
note

By the time you read this, you might simply be able to type python instead of python3.

Now, look inside the new test-venv directory. You’ll see a number of system-like directories such as bin, include, and lib. To activate the virtual environment, you need to source (not execute) the test-venv/bin/activate script:

$ . test-env/bin/activate
p. 418

The reason for sourcing the execution is that activation is essentially setting an environment variable, which you can’t do by running an executable. At this point, when you run Python, you get the version in test-venv/bin directory (which is itself only a symbolic link), and the VIRTUAL_ENV environment variable is set to the environment base directory. You can run deactivate to exit to the virtual environment.

It isn’t any more complicated than that. With this environment variable set, you get a new, empty packages library in test-venv/lib, and anything new you install when in the environment goes there instead of in the main system’s library.

Not all programming languages allow virtual environments in the way Python does, but it’s worth knowing about it, if for no other reason than to clear up some confusion about the word virtual.