find_executable

pyhelpers.dirs.find_executable(name, options=None, target=None, normalized=True, as_str=True)[source]

Find the pathname of an executable file for a specified application.

This function relies on _find_file_path() to check a known target pathname, search through options, and fall back to the system’s PATH, in that order.

Parameters:
  • name (str) – Name or filename of the application that is to be called.

  • options (list | set | None) – Possible pathnames or directories to search for the executable; defaults to None.

  • target (str | None) – Specific pathname of the executable file (if already known); this is checked first and, if it does not resolve to a valid match, the function stops and does not search options or the system PATH. Defaults to None.

  • normalized (bool) – Whether to format the returned pathname for display via _format_display_path(). If True, the pathname is returned as a formatted str; if False, it is returned unformatted as a pathlib.Path. Defaults to True.

  • as_str (bool) – Whether to return the path as a string; if False, a pathlib.Path object is returned instead. Defaults to True.

Returns:

Whether the specified executable file exists (i.e. a boolean indicating existence), together with its pathname, or None if it was not found.

Return type:

tuple[bool, pathlib.Path | str | None]

Examples:

>>> from pyhelpers.dirs import find_executable
>>> import os
>>> import sys

>>> python_exe = "python.exe"
>>> python_exe_exists, path_to_python_exe = find_executable(python_exe)
>>> python_exe_exists
True

>>> possible_paths = [os.path.dirname(sys.executable), sys.executable]
>>> target = possible_paths[0]  # a directory, not a file - not a valid target
>>> python_exe_exists, path_to_python_exe = find_executable(python_exe, target=target)
>>> python_exe_exists
False

>>> target = possible_paths[1]
>>> python_exe_exists, path_to_python_exe = find_executable(python_exe, target=target)
>>> python_exe_exists
True

>>> python_exe_exists, path_to_python_exe = find_executable(possible_paths[1])
>>> python_exe_exists
True

>>> text_exe = "pyhelpers.exe"  # This file does not actually exist
>>> test_exe_exists, path_to_test_exe = find_executable(text_exe, possible_paths)
>>> test_exe_exists
False
>>> path_to_test_exe is None
True