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.
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)
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)
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.
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)
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)