Python shutil.which() Examples

The following are 30 code examples for showing how to use shutil.which(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module shutil , or try the search function .

Example 1
Project: aegea   Author: kislyuk   File: ssm.py    License: Apache License 2.0 6 votes vote down vote up
def ensure_session_manager_plugin():
    session_manager_dir = os.path.join(config.user_config_dir, "bin")
    PATH = os.environ.get("PATH", "") + ":" + session_manager_dir
    if shutil.which("session-manager-plugin", path=PATH):
        subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
    else:
        os.makedirs(session_manager_dir, exist_ok=True)
        target_path = os.path.join(session_manager_dir, "session-manager-plugin")
        if platform.system() == "Darwin":
            download_session_manager_plugin_macos(target_path=target_path)
        elif platform.linux_distribution()[0] == "Ubuntu":
            download_session_manager_plugin_linux(target_path=target_path)
        else:
            download_session_manager_plugin_linux(target_path=target_path, pkg_format="rpm")
        os.chmod(target_path, stat.S_IRUSR | stat.S_IWUSR | stat.S_IXUSR)
        subprocess.check_call(["session-manager-plugin"], env=dict(os.environ, PATH=PATH))
    return shutil.which("session-manager-plugin", path=PATH) 
Example 2
Project: epr   Author: wustho   File: epr.py    License: MIT License 6 votes vote down vote up
def find_media_viewer():
    global VWR
    VWR_LIST = [
        "feh",
        "gio",
        "sxiv",
        "gnome-open",
        "gvfs-open",
        "xdg-open",
        "kde-open",
        "firefox"
    ]
    if sys.platform == "win32":
        VWR = ["start"]
    elif sys.platform == "darwin":
        VWR = ["open"]
    else:
        for i in VWR_LIST:
            if shutil.which(i) is not None:
                VWR = [i]
                break

    if VWR[0] in {"gio"}:
        VWR.append("open") 
Example 3
Project: toonapilib   Author: costastf   File: core_library.py    License: MIT License 6 votes vote down vote up
def get_binary_path(executable, logging_level='INFO'):
    """Gets the software name and returns the path of the binary."""
    if sys.platform == 'win32':
        if executable == 'start':
            return executable
        executable = executable + '.exe'
        if executable in os.listdir('.'):
            binary = os.path.join(os.getcwd(), executable)
        else:
            binary = next((os.path.join(path, executable)
                           for path in os.environ['PATH'].split(os.pathsep)
                           if os.path.isfile(os.path.join(path, executable))), None)
    else:
        venv_parent = get_venv_parent_path()
        venv_bin_path = os.path.join(venv_parent, '.venv', 'bin')
        if not venv_bin_path in os.environ.get('PATH'):
            if logging_level == 'DEBUG':
                print(f'Adding path {venv_bin_path} to environment PATH variable')
            os.environ['PATH'] = os.pathsep.join([os.environ['PATH'], venv_bin_path])
        binary = shutil.which(executable)
    return binary if binary else None 
Example 4
Project: rift-python   Author: brunorijsman   File: interop.py    License: Apache License 2.0 6 votes vote down vote up
def check_juniper_rift_in_path():
    if shutil.which("rift-environ") is None:
        fatal_error("Cannot find Juniper RIFT (rift-environ) in PATH")

    # run it and check version
    output = subprocess.check_output(["rift-environ",
                                      "--version"], universal_newlines=True)
    # print (output)
    regex = re.compile(r"^.hrift encoding schema: *(\d+)\.(\d+).*",
                       re.IGNORECASE  | re.MULTILINE)
    major = re.search(regex, output)

    if not major or not major.group(1):
        fatal_error("Cannot detect major version of Juniper RIFT")

    minor = major.group(2)
    major = major.group(1)

    expected_minor = protocol_minor_version
    expected_major = protocol_major_version

    if int(major) != expected_major or int(minor) != expected_minor:
        fatal_error("Wrong Major/Minor version of Juniper RIFT: (expected {}.{}, got {}.{})"
                    .format(expected_major, expected_minor, major, minor)) 
Example 5
Project: datasette   Author: simonw   File: common.py    License: Apache License 2.0 6 votes vote down vote up
def fail_if_publish_binary_not_installed(binary, publish_target, install_link):
    """Exit (with error message) if ``binary` isn't installed"""
    if not shutil.which(binary):
        click.secho(
            "Publishing to {publish_target} requires {binary} to be installed and configured".format(
                publish_target=publish_target, binary=binary
            ),
            bg="red",
            fg="white",
            bold=True,
            err=True,
        )
        click.echo(
            "Follow the instructions at {install_link}".format(
                install_link=install_link
            ),
            err=True,
        )
        sys.exit(1) 
Example 6
Project: typhon   Author: atmtools   File: common.py    License: MIT License 6 votes vote down vote up
def reraise_with_stack(func):
    """Make functions include the whole stack in raised exceptions

    Notes:
        This is a decorator function.

    When using the concurrent.futures module, the original traceback message
    gets lost, which makes it difficult to debug. This decorator solves the
    problem.

    References:
        Taken from https://stackoverflow.com/a/29357032.
    """

    @functools.wraps(func)
    def wrapped(*args, **kwargs):
        try:
            return func(*args, **kwargs)
        except Exception as e:
            traceback_str = traceback.format_exc()
            raise Exception(
                "Error occurred. Original traceback is\n%s\n" % traceback_str
            )

    return wrapped 
Example 7
Project: Obfuscapk   Author: ClaudiuGeorgiu   File: tool.py    License: MIT License 6 votes vote down vote up
def __init__(self):
        self.logger = logging.getLogger(
            "{0}.{1}".format(__name__, self.__class__.__name__)
        )

        if "APKTOOL_PATH" in os.environ:
            self.apktool_path: str = os.environ["APKTOOL_PATH"]
        else:
            self.apktool_path: str = "apktool"

        full_apktool_path = shutil.which(self.apktool_path)

        # Make sure to use the full path of the executable (needed for cross-platform
        # compatibility).
        if full_apktool_path is None:
            raise RuntimeError(
                'Something is wrong with executable "{0}"'.format(self.apktool_path)
            )
        else:
            self.apktool_path = full_apktool_path 
Example 8
Project: Obfuscapk   Author: ClaudiuGeorgiu   File: tool.py    License: MIT License 6 votes vote down vote up
def __init__(self):
        self.logger = logging.getLogger(
            "{0}.{1}".format(__name__, self.__class__.__name__)
        )

        if "JARSIGNER_PATH" in os.environ:
            self.jarsigner_path: str = os.environ["JARSIGNER_PATH"]
        else:
            self.jarsigner_path: str = "jarsigner"

        full_jarsigner_path = shutil.which(self.jarsigner_path)

        # Make sure to use the full path of the executable (needed for cross-platform
        # compatibility).
        if full_jarsigner_path is None:
            raise RuntimeError(
                'Something is wrong with executable "{0}"'.format(self.jarsigner_path)
            )
        else:
            self.jarsigner_path = full_jarsigner_path 
Example 9
Project: Obfuscapk   Author: ClaudiuGeorgiu   File: tool.py    License: MIT License 6 votes vote down vote up
def __init__(self):
        self.logger = logging.getLogger(
            "{0}.{1}".format(__name__, self.__class__.__name__)
        )

        if "ZIPALIGN_PATH" in os.environ:
            self.zipalign_path: str = os.environ["ZIPALIGN_PATH"]
        else:
            self.zipalign_path: str = "zipalign"

        full_zipalign_path = shutil.which(self.zipalign_path)

        # Make sure to use the full path of the executable (needed for cross-platform
        # compatibility).
        if full_zipalign_path is None:
            raise RuntimeError(
                'Something is wrong with executable "{0}"'.format(self.zipalign_path)
            )
        else:
            self.zipalign_path = full_zipalign_path 
Example 10
Project: ungoogled-chromium   Author: Eloston   File: patches.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _apply_callback(args, parser_error):
    logger = get_logger()
    patch_bin_path = None
    if args.patch_bin is not None:
        patch_bin_path = Path(args.patch_bin)
        if not patch_bin_path.exists():
            patch_bin_path = shutil.which(args.patch_bin)
            if patch_bin_path:
                patch_bin_path = Path(patch_bin_path)
            else:
                parser_error(
                    f'--patch-bin "{args.patch_bin}" is not a command or path to executable.')
    for patch_dir in args.patches:
        logger.info('Applying patches from %s', patch_dir)
        apply_patches(
            generate_patches_from_series(patch_dir, resolve=True),
            args.target,
            patch_bin_path=patch_bin_path) 
Example 11
Project: pdbpp   Author: pdbpp   File: pdbpp.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setbgcolor(line, color):
    # hack hack hack
    # add a bgcolor attribute to all escape sequences found
    import re
    setbg = '\x1b[%sm' % color
    regexbg = '\\1;%sm' % color
    result = setbg + re.sub('(\x1b\\[.*?)m', regexbg, line) + '\x1b[00m'
    if os.environ.get('TERM') == 'eterm-color':
        # it seems that emacs' terminal has problems with some ANSI escape
        # sequences. Eg, 'ESC[44m' sets the background color in all terminals
        # I tried, but not in emacs. To set the background color, it needs to
        # have also an explicit foreground color, e.g. 'ESC[37;44m'. These
        # three lines are a hack, they try to add a foreground color to all
        # escape sequences which are not recognized by emacs. However, we need
        # to pick one specific fg color: I choose white (==37), but you might
        # want to change it.  These lines seems to work fine with the ANSI
        # codes produced by pygments, but they are surely not a general
        # solution.
        result = result.replace(setbg, '\x1b[37;%dm' % color)
        result = result.replace('\x1b[00;%dm' % color, '\x1b[37;%dm' % color)
        result = result.replace('\x1b[39;49;00;', '\x1b[37;')
    return result 
Example 12
Project: pdbpp   Author: pdbpp   File: pdbpp.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _disable_pytest_capture_maybe(self):
        try:
            import py.test
            # Force raising of ImportError if pytest is not installed.
            py.test.config
        except (ImportError, AttributeError):
            return
        try:
            capman = py.test.config.pluginmanager.getplugin('capturemanager')
            capman.suspendcapture()
        except KeyError:
            pass
        except AttributeError:
            # Newer pytest with support ready, or very old py.test for which
            # this hack does not work.
            pass 
Example 13
Project: pdbpp   Author: pdbpp   File: pdbpp.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _install_linecache_wrapper(self):
        """Disable linecache.checkcache to not invalidate caches.

        This gets installed permanently to also bypass e.g. pytest using
        `inspect.getsource`, which would invalidate it outside of the
        interaction them.
        """
        if not hasattr(self, "_orig_linecache_checkcache"):
            import linecache

            # Save it, although not used really (can be useful for debugging).
            self._orig_linecache_checkcache = linecache.checkcache

            def _linecache_checkcache(*args, **kwargs):
                return

            linecache.checkcache = _linecache_checkcache 
Example 14
Project: pdbpp   Author: pdbpp   File: pdbpp.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def do_track(self, arg):
        """
        track expression

        Display a graph showing which objects are referred by the
        value of the expression.  This command requires pypy to be in
        the current PYTHONPATH.
        """
        try:
            from rpython.translator.tool.reftracker import track
        except ImportError:
            print('** cannot import pypy.translator.tool.reftracker **',
                  file=self.stdout)
            return
        try:
            val = self._getval(arg)
        except:
            pass
        else:
            track(val) 
Example 15
Project: pdbpp   Author: pdbpp   File: pdbpp.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_editor_cmd(self, filename, lineno):
        editor = self.config.editor
        if editor is None:
            try:
                editor = os.environ["EDITOR"]
            except KeyError:
                try:
                    from shutil import which
                except ImportError:
                    from distutils.spawn import find_executable as which
                editor = which("vim")
                if editor is None:
                    editor = which("vi")
            if not editor:
                raise RuntimeError("Could not detect editor. Configure it or set $EDITOR.")  # noqa: E501
        return self._format_editcmd(editor, filename, lineno) 
Example 16
Project: pdbpp   Author: pdbpp   File: pdbpp.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def set_trace(self, frame=None):
        """Remember starting frame.

        This is used with pytest, which does not use pdb.set_trace().
        """
        if getattr(local, "_pdbpp_completing", False):
            # Handle set_trace being called during completion, e.g. with
            # fancycompleter's attr_matches.
            return
        if self.disabled:
            return

        if frame is None:
            frame = sys._getframe().f_back
        self._via_set_trace_frame = frame
        self._stopped_for_set_trace = False

        self.start_filename = frame.f_code.co_filename
        self.start_lineno = frame.f_lineno

        return super(Pdb, self).set_trace(frame) 
Example 17
Project: renpy-shader   Author: bitsawer   File: util.py    License: MIT License 6 votes vote down vote up
def _get_soname(f):
            # assuming GNU binutils / ELF
            if not f:
                return None
            objdump = shutil.which('objdump')
            if not objdump:
                # objdump is not available, give up
                return None

            try:
                proc = subprocess.Popen((objdump, '-p', '-j', '.dynamic', f),
                                        stdout=subprocess.PIPE,
                                        stderr=subprocess.DEVNULL)
            except OSError:  # E.g. bad executable
                return None
            with proc:
                dump = proc.stdout.read()
            res = re.search(br'\sSONAME\s+([^\s]+)', dump)
            if not res:
                return None
            return os.fsdecode(res.group(1)) 
Example 18
Project: spleeter   Author: deezer   File: ffmpeg.py    License: MIT License 5 votes vote down vote up
def _check_ffmpeg_install():
    """ Ensure FFMPEG binaries are available.

    :raise SpleeterError: If ffmpeg or ffprobe is not found.
    """
    for binary in ('ffmpeg', 'ffprobe'):
        if shutil.which(binary) is None:
            raise SpleeterError('{} binary not found'.format(binary)) 
Example 19
Project: cmus-osx   Author: PhilipTrauner   File: util.py    License: MIT License 5 votes vote down vote up
def locate_editor() -> Optional[Path]:
    for editor in (getenv("VISUAL", None), getenv("EDITOR", None), "nano", "vim", "vi"):
        if editor is not None:
            # Might be absolute path to editor
            editor_path = Path(editor).expanduser()
            # Might also be just the binary name
            editor_which = which(editor)

            if editor_path.is_file():
                return editor_path
            elif editor_which is not None:
                return Path(editor_which)
    return None 
Example 20
Project: QCElemental   Author: MolSSI   File: importing.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def which(
    command: str, *, return_bool: bool = False, raise_error: bool = False, raise_msg: str = None, env: str = None
) -> Union[bool, None, str]:
    """Test to see if a command is available.

    Returns
    -------
    str or None
        By default, returns command path if command found or `None` if not.
        Environment is $PATH or `os.pathsep`-separated `env`, less any None values.
    bool
        When `return_bool=True`, returns whether or not found.

    Raises
    ------
    ModuleNotFoundError
        When `raises_error=True` and command not found. Raises generic message plus any `raise_msg`.

    """
    if env is None:
        lenv = {"PATH": os.pathsep + os.environ.get("PATH", "") + os.path.dirname(sys.executable)}
    else:
        lenv = {"PATH": os.pathsep.join([os.path.abspath(x) for x in env.split(os.pathsep) if x != ""])}
    lenv = {k: v for k, v in lenv.items() if v is not None}

    ans = shutil.which(command, mode=os.F_OK | os.X_OK, path=lenv["PATH"])

    if raise_error and ans is None:
        raise ModuleNotFoundError(
            f"Command '{command}' not found in envvar PATH.{' ' + raise_msg if raise_msg else ''}"
        )

    if return_bool:
        return bool(ans)
    else:
        return ans 
Example 21
Project: audio   Author: pytorch   File: test_case_utils.py    License: BSD 2-Clause "Simplified" License 5 votes vote down vote up
def skipIfNoExec(cmd):
    return unittest.skipIf(shutil.which(cmd) is None, f'`{cmd}` is not available') 
Example 22
Project: HardRLWithYoutube   Author: MaxSobolMark   File: mpi_util.py    License: MIT License 5 votes vote down vote up
def gpu_count():
    """
    Count the GPUs on this machine.
    """
    if shutil.which('nvidia-smi') is None:
        return 0
    output = subprocess.check_output(['nvidia-smi', '--query-gpu=gpu_name', '--format=csv'])
    return max(0, len(output.split(b'\n')) - 2) 
Example 23
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: partial.py    License: MIT License 5 votes vote down vote up
def __init__(self, config=path_config.config_path_file):
        self.conf = config
        GeneralClass.__init__(self, self.conf)
        if shutil.which('mysqlfrm') is None:
            logger.critical("Could not find mysqlfrm! Please install it or check if it is in PATH")
            raise RuntimeError("Could not find mysqlfrm! Please install it or check if it is in PATH") 
Example 24
Project: MySQL-AutoXtraBackup   Author: ShahriyarR   File: partial.py    License: MIT License 5 votes vote down vote up
def final_actions(self):
        # Type Database name of table which you want to restore
        database_name = input("Type Database name: ")
        # Type name of table which you want to restore
        table_name = input("Type Table name: ")
        path = self.get_table_ibd_file(
            database_name=database_name,
            table_name=table_name)
        path_to_mysql_datadir = self.datadir + "/" + database_name

        if path:
            path_to_frm_file = path[:-3] + 'frm'

        obj_check_env = check_env.CheckEnv(self.conf)

        if path:
            try:
                obj_check_env.check_mysql_uptime()
                self.check_innodb_file_per_table()
                self.check_mysql_version()
                self.check_database_exists_on_mysql(
                                    database_name=database_name)
                self.check_table_exists_on_mysql(
                                    path_to_frm_file=path_to_frm_file,
                                    database_name=database_name,
                                    table_name=table_name)
                self.lock_table(database_name=database_name, table_name=table_name)
                self.alter_tablespace(database_name=database_name, table_name=table_name)
                self.copy_ibd_file_back(path_of_ibd_file=path, path_to_mysql_database_dir=path_to_mysql_datadir)
                self.give_chown(path_to_mysql_database_dir=path_to_mysql_datadir)
                self.import_tablespace(database_name=database_name, table_name=table_name)
                self.unlock_tables()
            except Exception as err:
                logger.error("FAILED: Table is not recovered")
                logger.error(err)
                raise RuntimeError("FAILED: Table is not recovered")
            else:
                logger.info("OK: Table Recovered! ...")
                return True 
Example 25
Project: pwnypack   Author: edibledinos   File: asm.py    License: MIT License 5 votes vote down vote up
def find_binutils_prefix(arch):
    global BINUTILS_PREFIXES

    prefix = BINUTILS_PREFIXES.get(arch)
    if prefix is not None:
        return prefix

    for suffix in BINUTILS_SUFFIXES:
        prefix = '%s-%s' % (arch, suffix)
        if shutil.which('%sas' % prefix) and \
                shutil.which('%sld' % prefix):
            BINUTILS_PREFIXES[arch] = prefix
            return prefix
    else:
        raise RuntimeError('Could not locate a suitable binutils for %s.' % arch) 
Example 26
Project: zun   Author: openstack   File: status.py    License: Apache License 2.0 5 votes vote down vote up
def _cmd_exists(self, cmd):
        try:
            return shutil.which(cmd) is not None
        except AttributeError:
            # shutil.which is not available in python 2.x so try an
            # alternative approach
            return any(
                os.access(os.path.join(path, cmd), os.X_OK)
                for path in os.environ["PATH"].split(os.pathsep)
            ) 
Example 27
Project: deoplete-swift   Author: landaire   File: swift.py    License: MIT License 5 votes vote down vote up
def validate_command(path):
        if os.access(path, mode=os.X_OK):
            return path

        default = shutil.which('sourcekitten', mode=os.X_OK)
        if default is None:
            raise SourceKittenNotFound(default)

        return default 
Example 28
Project: rift-python   Author: brunorijsman   File: interop.py    License: Apache License 2.0 5 votes vote down vote up
def check_pytest_in_path():
    if shutil.which("pytest") is None:
        fatal_error("Cannot find pytest in PATH") 
Example 29
Project: raveberry   Author: raveberry   File: system.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def _get_mopidy_config() -> str:
        if shutil.which("cava"):
            # if cava is installed, use the visualization config for mopidy
            config_file = os.path.join(settings.BASE_DIR, "setup/mopidy_cava.conf")
        else:
            config_file = os.path.join(settings.BASE_DIR, "setup/mopidy.conf")
        return config_file 
Example 30
Project: qutebrowser   Author: qutebrowser   File: conftest.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _get_echo_exe_path():
    """Return the path to an echo-like command, depending on the system.

    Return:
        Path to the "echo"-utility.
    """
    if utils.is_windows:
        return os.path.join(testutils.abs_datapath(), 'userscripts',
                            'echo.bat')
    else:
        return shutil.which("echo")