DepUnPr

ita · eng

Auto-activate Python virtualenv in bash on directory change

The unnecessary replacement of `cd` which automatically activate and deactivate Python virtualenvs.

I like to develop unnecessary things, and often I like to develop them with Python.

When I can, I try to develop with current Debian Python version and packaged libraries, but sometime this is impossible. Or it would be unnecessary difficult to do.

I this cases I create a virtualenv, using Python venv module:

python3 -m venv venv

(my virtualenvs are usually in venv or .venv folders)

I know, there are n+1 programs which handle virtualenv creation and so on, but using them require to have the correct tool installed. And, anyway, I said that this is unnecessary, did I?

I also made an alias to speed up this step:

alias py='python3 -m'

so that I can condense the command as

py venv venv

But then another non-problem arisen: I need to remember to activate the virtualenv when I’m fiddling with the project and, more important, I need to remember to deactivate it when I change project.

How many time I have run commands for project_b inside the virtualenv of project_a? Once too many.

So I decided to do the only thing appropriate: an unnecessary replacement of cd which automatically activate and deactivate Python virtualenvs.

The script define a function which is then aliased to cd. After changing directory, the script search for a folder called venv or .venv in CWD or in parent directories (up to the home). If it finds one it activate it, not before deactivating the one currently active (if any).

Obviously someone immediately declared the intent to create a git repo with a malicious venv/bin/activate script and trick me to clone it.

So I had to add a approve/block list functionality. (which may sound necessary, given the threat, but as nobody should use this script, is it still unnecessary, and thus approved by this Department)

Now the script when find a virtualenv, check if it is in one of the two lists. If it is allowed, it activates it right away, if it is blocked it ignores it. If it is not either, it asks to the user what to do, and puts it in the correct list for future reference.

It works? yes.
It is necessary? no.
Should anyone really use this? no.

Anyway, here is the script:

https://paste.sr.ht/~fabrixxm/fe248f12bc7c190ddca59769e0be1f41d8f62a4e