From: Frank Brehm Date: Thu, 23 Mar 2017 16:45:03 +0000 (+0100) Subject: Adding method get_command() to class PpApplication X-Git-Tag: 0.1.2~222 X-Git-Url: https://git.uhu-banane.net/?a=commitdiff_plain;h=e628b939ad94cd30f0797b0b1f1c8bbd1ed31ff7;p=pixelpark%2Fadmin-tools.git Adding method get_command() to class PpApplication --- diff --git a/pp_lib/app.py b/pp_lib/app.py index f63ed9c..1fe1172 100644 --- a/pp_lib/app.py +++ b/pp_lib/app.py @@ -28,12 +28,13 @@ from .global_version import __version__ as __global_version__ from .errors import FunctionNotImplementedError, PpAppError from .common import pp, terminal_can_colors, to_bytes +from .common import caller_search_path from .colored import ColoredFormatter, colorstr from .obj import PpBaseObjectError, PpBaseObject -__version__ = '0.3.2' +__version__ = '0.3.3' LOG = logging.getLogger(__name__) @@ -743,6 +744,61 @@ class PpApplication(PpBaseObject): return msg return colorstr(msg, color) + # ------------------------------------------------------------------------- + def get_command(self, cmd, quiet=False): + """ + Searches the OS search path for the given command and gives back the + normalized position of this command. + If the command is given as an absolute path, it check the existence + of this command. + + @param cmd: the command to search + @type cmd: str + @param quiet: No warning message, if the command could not be found, + only a debug message + @type quiet: bool + + @return: normalized complete path of this command, or None, + if not found + @rtype: str or None + + """ + + if self.verbose > 2: + LOG.debug("Searching for command {!r} ...".format(cmd)) + + # Checking an absolute path + if os.path.isabs(cmd): + if not os.path.exists(cmd): + LOG.warning("Command {!r} doesn't exists.".format(cmd)) + return None + if not os.access(cmd, os.X_OK): + msg = "Command {!r} is not executable.".format(cmd) + LOG.warning(msg) + return None + return os.path.normpath(cmd) + + # Checking a relative path + for d in caller_search_path(): + if self.verbose > 3: + LOG.debug("Searching command in {!r} ...".format(d)) + p = os.path.join(d, cmd) + if os.path.exists(p): + if self.verbose > 2: + LOG.debug("Found {!r} ...".format(p)) + if os.access(p, os.X_OK): + return os.path.normpath(p) + else: + LOG.debug("Command {!r} is not executable.".format(p)) + + # command not found, sorry + if quiet: + if self.verbose > 2: + LOG.debug("Command {!r} not found.".format(cmd)) + else: + LOG.warning("Command {!r} not found.".format(cmd)) + + return None # =============================================================================