List executables that are in $PATH without knowing their locations

Question:

Is there a way to (glob-like) list executables that match a certain pattern without knowing their actual locations? For example, let’s say I have multiple versions of GCC installed: gcc-10, gcc-11 and gcc-12, then I need the pattern gcc-* to yield something like ['gcc-10', 'gcc-11', 'gcc-12'].

The behavior I’m after is equivalent to writing gcc- and then hitting tab in a Unix shell.

Asked By: thomas_f

||

Answers:

You could get the PATH environment variable, split it, then run a glob search on each extracted directory.

import os
from glob import glob
paths = os.environ.get("PATH", "").split(os.path.pathsep)
glob_pattern = "gcc-*"
found = []
for path in paths:
    found.extend(glob(os.path.join(path, glob_pattern)))
print(found)
Answered By: tdelaney

You would have to iterate over the contents of PATH, then iterate over the files in each directory to check if they are executable. (Basically, you need to re-implement the core functionality of the which command.) Something like

for d in os.environ['PATH'].split(':'):
    for f in pathlib.Path(d).glob('gcc-*'):
        if os.access(f, os.X_OK):
            print(f)
Answered By: chepner
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.