How to create Python virtual environment on Ubuntu (activate and deactivate it)

When working on a Python project to develop new applications, it is always advisable to use a virtual environment. This way, your project is isolated from the system environment. If you want to use a particular package version for your project, you can install it in your environment without affecting the whole system; it’s always recommended in a shared environment where different users might have other requirements. Python environment gives you the flexibility to create a new environment for each project and install packages as per your need. Each virtual environment has its own Python binary (which matches the version of the binary used to create this environment) and can have its own independent set of installed Python packages in its site directories. When you switch projects, you can create a new virtual environment and not worry about breaking the packages installed in the other environments.

In this post, I will show how to create a virtual environment for a Python project and how to activate and deactivate it.

Creating virtual environment:

You can create a virtual environment for your Python project by executing the command venv.

python3 -m venv /path/to/new/virtual/environment

The venv module creates lightweight virtual environment with its own site directories, optionally isolated from system site directories. This command creates the target directory and places a pyvenv.cfg file in it with a home key pointing to the Python installation from which the command was run. It also creates a bin subdirectory containing a copy/symlink of the Python binary/binaries.

Activating a virtual environment:

Before installing Python packages in the virtual environment or using it, you need to activate it. Activating a virtual environment will put the virtual environment-specific python and pip executables into your shell’s PATH. To activate a virtual environment, run the following command:

source env/bin/activate

Deactivating the virtual environment:

If you want to switch to another project or otherwise leave your virtual environment, you need to deactivate the environment. Run the following command to deactivate it:

deactivate

References:

  1. Creation of python environments

Similar Posts

Leave a Reply

Your email address will not be published.

This site uses Akismet to reduce spam. Learn how your comment data is processed.