Using Python Virtual Environments Comfortably

Richard Dubniczky
2 min readMar 28, 2022

--

While using python, you’ve probably had the problem of needing to use two (or more) different versions of packages. This is a major problem for python developers who need to jump quickly between projects. So much so, that there are now multiple ways of solving this problem, all with their own advantages and drawbacks.

One of the most common ways is by using a virtual environment (venv). You create and activate a virtual environment in your current project, then install all necessary packages. The catch is, doing this with the built-in venv module is not convenient. Here is an example of how you’d do it normally:

  1. Create environment
python -m venv .venv

2. Activate environment

source .venv/bin/activate

3. Install packages

pip install -r requirements.txt

4. Create lock file to save versions

pip freeze > pip.lock

Now you are ready to use your virtual environment. If you’d like to install additional packages, you’d need to add them to the requirements file, then do the steps from 3. over again.

This is of course tedious and requires repetition, so let’s optimize the repetition out of this!

The Solution

We are going to use a Linux terminal extension to optimize this process. If you are using Windows, you can easily install WSL ubuntu and proceed there.

1. Clone the following repository:

git clone https://gitlab.com/richardnagy/python-venv-terminal-extension

2. Install the terminal extension

cd ./python-venv-terminal-extension
./install.sh

3. Restart your terminal

bash

Now you can use the commands given to you by the package. Let’s take a look at a few of the important ones.

venv load

The load command will create a virtual environment in your current directory, activate it, and install packages from requirements.txt (or from pip.lock if it exists). Additionally, it will update pip.lock every time you add a new package.

venv run

The run command runs your current project, if it finds a __main__.py or main.py file in the root folder.

venv add [name]

Adds the given package to requirements, installs it and creates a lock entry for it.

These are only some of the features of this extension, feel free to experiment yourself and check out the repository readme for more information.

Improvement suggestions and merge requests are always welcome!

Thank you for reading, hope to help you with efficient coding!

Richard

--

--

Richard Dubniczky
Richard Dubniczky

Written by Richard Dubniczky

Security/Infrastructure Enginner, Full-Stack software developer, Cryptography MSC

No responses yet