ondir

I recently started to use ondir, which appears to be able to save me some keystrokes when switching to Python project directories where I have a virtual environment set up. The virtual environment will be automatically activated when I enter the project directory, and deactivated when I leave the directory. That seems quite useful. I will quite likely forget how this is set up so here are some notes.

After installing ondir Debian package, add this to ~/.bashrc:

# Use ondir for automatic virtualenv activation
source /usr/share/ondir/integration/bash

And then add this to ~/.ondirrc:

enter ~/projects/([^/]+)
  if [ -r .venv ]; then
    . ./.venv/bin/activate
  fi

leave ~/projects/([^/]+)
  deactivate > /dev/null 2>&1

A somewhat fancier alternative to ondir is direnv, which would be the easy choice on Fedora because ondir has not been packaged for Fedora, but direnv has a Fedora package. However the version of direnv on Fedora 40 emits some warnings about some Python library or other getting deprecated. I found those warnings annoying and distracting and decided not to bother.

I have also configured pip to always require a virtual environment:

$ pip config list
global.require-virtualenv='True'

Further, I use pipx to install Python applications. Requiring virtual environments and using pipx help avoid the mess from pip install-ing stuff.

(Posted on July 2, 2024.)