brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: shutil.which checks if a command exists before you call it

Scripting
~/tips/tip-python-shutil-which

import shutil

Returns the full path of a command, or None when it is not installed.

A script that calls an external tool and dies with a stack trace because the tool is not installed gives a poor error message. A one-line check fixes that.

shutil.which(cmd) returns the path of the executable that would run, or None if nothing would:

import shutil

if shutil.which("ffmpeg") is None:
    raise SystemExit("ffmpeg is not installed")

The same call is useful when you want the full path for a message or a subprocess call:

print(shutil.which("git"))
# /usr/bin/git

It reads PATH from the environment by default. Pass your own search path with path=, for example shutil.which("git", path="/nonexistent"), which returns None. By default it checks that the file exists and is executable, and the mode argument changes that. On Windows it uses PATHEXT to resolve commands without an extension, so "python" can find python.EXE.

Caveats: if the command contains a directory part, the docs say which() checks only that path and does not search PATH, so shutil.which("bin/git") looks for bin/git relative to the current directory. And it tells you the program exists, not that it is the right version. If you need a minimum version, run it with --version afterwards and read the output.

Further reading: shutil.which

More Scripting tips import difflib $r = Invoke-RestMethod https://api.github.com/repos/PowerShell/PowerShell/releases/latest import json, os, tempfile from collections import Counter from contextlib import chdir All Scripting tips (10) All topics

Link