Skip to content

Instantly share code, notes, and snippets.

@smokey42
Created September 16, 2023 13:41
Show Gist options
  • Save smokey42/59314fb0a4c79081045ce7686ea0b8ba to your computer and use it in GitHub Desktop.
Save smokey42/59314fb0a4c79081045ce7686ea0b8ba to your computer and use it in GitHub Desktop.
A utility to find the location(s) of an executable in the PATH environment variable.
#!/usr/bin/env python3
"""A utility to find the location(s) of an executable in the PATH environment variable.
This script searches for an executable specified as a command-line argument
in the directories listed in the PATH environment variable. It supports
options to display symbolic links.
Usage:
zzat executable_name [-l|--links]
"""
import argparse
import os
import sys
import textwrap
def find_executable(exec_name, show_links=False):
"""Find the path(s) of a given executable in the PATH environment variable.
This function searches through the PATH environment variable to find all
occurrences of an executable. It returns a list of paths where the
executable is found. Optionally, it can also show where symbolic links
point to.
Args:
exec_name (str): The name of the executable to search for.
show_links (bool, optional): Whether to show symbolic links. Defaults to False.
Returns:
list: A list of paths where the executable is found. Each entry can optionally
show the target of symbolic links.
"""
path_var = os.environ.get("PATH", "")
path_components = path_var.split(":")
# Deduplicate entries
seen = set()
dedup_path_components = []
for component in path_components:
if component not in seen:
dedup_path_components.append(component)
seen.add(component)
found_in = []
for path in dedup_path_components:
exec_path = os.path.join(path, exec_name)
if os.path.isfile(exec_path) and os.access(exec_path, os.X_OK):
if show_links and os.path.islink(exec_path):
link_dest = os.readlink(exec_path)
exec_path = f"{exec_path} -> {link_dest}"
found_in.append(exec_path)
return found_in
def main():
"""Entry point for the (wha)zzat program.
This function parses command-line arguments and finds the location(s) of a given
executable in the PATH environment variable. It prints the path(s) to stdout and
handles the optional flag to display symbolic links.
"""
parser = argparse.ArgumentParser(
description=textwrap.dedent(__doc__),
formatter_class=argparse.RawDescriptionHelpFormatter,
)
parser.add_argument(
"executable_name",
help="Name of the executable to search for",
)
parser.add_argument(
"-l",
"--links",
help="Show symbolic links",
action="store_true",
)
args = parser.parse_args()
found_in = find_executable(args.executable_name, args.links)
if found_in:
for path in found_in:
print(path)
else:
print(
f"The executable '{args.executable_name}' "
"was not found in any PATH components.",
file=sys.stderr,
)
if __name__ == "__main__":
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment