Python Environments on Linux

Python Environments on Linux

Creating a virtual environment will limit anything you do to that environment only, and no dependency installations will escape onto your host system. Creating a brand new environment per-project is a great habit to get into, or at the very least restricting all of your (my) messing around to a disposable test environment.

If you don't appreciate the impact of making system-wide Python changes to your host, I would encourage you to try "sudo apt remove python*" on a virtual desktop machine one day. For now, make sure to get into the habit of creating a new virtual environment for every project you do.

The below will create and initialize a brand new virtual environment directory within your current working directory:


virtualenv <project name>
source <project name>/bin/activate


python -m venv <project name>
source <project name>/bin/activate

Within the environment, feel free to make modifications to your Python installation, and to manage packages through PIP, safe in the knowledge that all changes are restricted to your current directory.

Once development has been completed, you can run pip freeze > requirements.txt to export all packages within the virtual environment to a file.

Exporting your environment packages to a .txt file is a great way of keeping tracking of all project dependencies during development. This also makes it easy to migrate your code to new environments, where all requisites can be sourced on the new host with pip install -r requirements.txt for an easy deployment.

Related Article