Python os.X_OK() Examples

The following are code examples for showing how to use os.X_OK(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: godot-mono-builds   Author: godotengine   File: os_utils.py    MIT License 7 votes vote down vote up
def find_executable(name) -> str:
    is_windows = os.name == 'nt'
    windows_exts = ENV_PATH_SEP.split(os.environ['PATHEXT']) if is_windows else None
    path_dirs = ENV_PATH_SEP.split(os.environ['PATH'])

    search_dirs = path_dirs + [os.getcwd()] # cwd is last in the list

    for dir in search_dirs:
        path = os.path.join(dir, name)

        if is_windows:
            for extension in windows_exts:
                path_with_ext = path + extension

                if os.path.isfile(path_with_ext) and os.access(path_with_ext, os.X_OK):
                    return path_with_ext
        else:
            if os.path.isfile(path) and os.access(path, os.X_OK):
                return path

    return '' 
Example 2
Project: leapp-repository   Author: oamg   File: library.py    Apache License 2.0 6 votes vote down vote up
def _get_cmd_output(cmd, delim, expected_len):
    ''' Verify if command exists and return output '''
    if not any(os.access(os.path.join(path, cmd[0]), os.X_OK) for path in os.environ['PATH'].split(os.pathsep)):
        api.current_logger().warning("'%s': command not found" % cmd[0])
        raise StopIteration

    try:
        # FIXME: Will keep call to subprocess until our stdlib supports "env" parameter
        # when there is any fd except 0,1,2 open, lvm closes the fd and prints a warning.
        # In our case /dev/urandom has other fd opened, probably for caching purposes.
        output = subprocess.check_output(cmd, env={'LVM_SUPPRESS_FD_WARNINGS': '1', 'PATH': os.environ['PATH']})

    except subprocess.CalledProcessError as e:
        api.current_logger().debug("Command '%s' return non-zero exit status: %s" % (" ".join(cmd), e.returncode))
        raise StopIteration

    for entry in output.split('\n'):
        entry = entry.strip()
        if not entry:
            continue

        data = entry.split(delim)
        data.extend([''] * (expected_len - len(data)))

        yield data 
Example 3
Project: pyblish-win   Author: pyblish   File: uuid.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def _popen(command, args):
    import os
    path = os.environ.get("PATH", os.defpath).split(os.pathsep)
    path.extend(('/sbin', '/usr/sbin'))
    for dir in path:
        executable = os.path.join(dir, command)
        if (os.path.exists(executable) and
            os.access(executable, os.F_OK | os.X_OK) and
            not os.path.isdir(executable)):
            break
    else:
        return None
    # LC_ALL to ensure English output, 2>/dev/null to prevent output on
    # stderr (Note: we don't have an example where the words we search for
    # are actually localized, but in theory some system could do so.)
    cmd = 'LC_ALL=C %s %s 2>/dev/null' % (executable, args)
    return os.popen(cmd) 
Example 4
Project: python-sii   Author: voipir   File: shell.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def which(program, fail=True):
    """ Sort of replicates the `which` utility.
    """
    is_exe    = lambda fp: os.path.isfile(fp) and os.access(fp, os.X_OK)
    locations = [os.path.join(path, program) for path in os.environ["PATH"].split(os.pathsep)]
    found     = [loc for loc in locations if is_exe(loc)]

    if not found:
        if not fail:
            return False
        else:
            raise RuntimeError("Did not find program: <{0}>".format(program))
    elif len(found) > 1:
        if not fail:
            return False
        else:
            raise RuntimeError("Found more than one instance of the program:\n"
                               "{0}".format('\n'.join(found)))
    else:
        return found[0] 
Example 5
Project: qt_moc_generator   Author: davidc604   File: qt_moc_generator.py    MIT License 6 votes vote down vote up
def which(program):
    import os
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None 
Example 6
Project: mimic   Author: googlearchive   File: target_env.py    Apache License 2.0 6 votes vote down vote up
def _Access(self, original, path, mode):
    """Replacement for os.access."""
    if self._IsStaticFile(path) or self._IsSkippedFile(path):
      # static files and skipped files are inaccessible to script code
      return False

    in_target, path = _ResolvePath(path)
    if in_target:
      if self._tree.HasFile(path):
        # modes W_OK and X_OK are never allowed
        return mode & (os.X_OK | os.W_OK) == 0
      elif self._tree.HasDirectory(path):
        # mode W_OK is not allowed
        return mode & os.W_OK == 0
      else:
        return False
    else:
      return original(path, mode)

  # patches for the os module 
Example 7
Project: define   Author: SethDusek   File: define.py    BSD 2-Clause "Simplified" License 6 votes vote down vote up
def which(program):
    import os

    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for pathh in os.environ["PATH"].split(os.pathsep):
            pathh = pathh.strip('"')
            exe_file = os.path.join(pathh, program)
            if is_exe(exe_file):
                return exe_file

    return None 
Example 8
Project: ngo-addons-backport   Author: camptocamp   File: which.py    GNU Affero General Public License v3.0 6 votes vote down vote up
def which(file, mode=F_OK | X_OK, path=None, pathext=None):
    """ Locate a file in a path supplied as a part of the file name,
        or the user's path, or a supplied path.
        The function returns full path (not necessarily absolute path),
        in which the given file name matches an existing file in a directory on the path,
        or raises IOError(errno.ENOENT).

        >>> # for doctest see which_files()
    """
    try:
        return iter(which_files(file, mode, path, pathext)).next()
    except StopIteration:
        try:
            from errno import ENOENT
        except ImportError:
            ENOENT = 2
        raise IOError(ENOENT, '%s not found' % (mode & X_OK and 'command' or 'file'), file) 
Example 9
Project: smoke-zephyr   Author: zeroSteiner   File: utilities.py    BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def which(program):
	"""
	Locate an executable binary's full path by its name.

	:param str program: The executables name.
	:return: The full path to the executable.
	:rtype: str
	"""
	# requirements = os
	is_exe = lambda fpath: (os.path.isfile(fpath) and os.access(fpath, os.X_OK))
	for path in os.environ['PATH'].split(os.pathsep):
		path = path.strip('"')
		exe_file = os.path.join(path, program)
		if is_exe(exe_file):
			return exe_file
	if is_exe(program):
		return os.path.abspath(program)
	return None 
Example 10
Project: git-stats-all   Author: arruda   File: git_stats_all.py    MIT License 6 votes vote down vote up
def which(program):
    """
    Return full path to exec if it exist in PATH, or else return None
    """
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:

        if is_exe(program):
            return program

    else:

        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None 
Example 11
Project: py-solc   Author: ethereum   File: install_solc.py    MIT License 6 votes vote down vote up
def is_executable_available(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath = os.path.dirname(program)
    if fpath:
        if is_exe(program):
            return True
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return True

    return False 
Example 12
Project: py-solc   Author: ethereum   File: filesystem.py    MIT License 6 votes vote down vote up
def is_executable_available(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath = os.path.dirname(program)
    if fpath:
        if is_exe(program):
            return True
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return True

    return False 
Example 13
Project: py-solc   Author: ethereum   File: install.py    MIT License 6 votes vote down vote up
def is_executable_available(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath = os.path.dirname(program)
    if fpath:
        if is_exe(program):
            return True
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return True

    return False 
Example 14
Project: clamavmirror   Author: akissa   File: setup.py    Mozilla Public License 2.0 6 votes vote down vote up
def get_readme():
    """Generate long description"""
    pandoc = None
    for path in os.environ["PATH"].split(os.pathsep):
        path = path.strip('"')
        pandoc = os.path.join(path, 'pandoc')
        if os.path.isfile(pandoc) and os.access(pandoc, os.X_OK):
            break
    try:
        if pandoc:
            cmd = [pandoc, '-t', 'rst', 'README.md']
            long_description = os.popen(' '.join(cmd)).read()
        else:
            raise ValueError
    except BaseException:
        long_description = open("README.md").read()
    return long_description 
Example 15
Project: WiFi-Pumpkin   Author: wi-fi-analyzer   File: StartMSF.py    GNU General Public License v3.0 6 votes vote down vote up
def which(program):
    '''
        Source: http://stackoverflow.com/questions/377017/test-if-executable-exists-in-python
    '''
    def is_exe(fpath):
        return os.path.exists(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file
    return None 
Example 16
Project: senf   Author: quodlibet   File: ls.py    MIT License 6 votes vote down vote up
def main(argv):
    dir_ = argv[1]
    for entry in sorted(os.listdir(dir_)):
        path = os.path.join(dir_, entry)
        size = os.path.getsize(path)
        mtime = os.path.getmtime(path)
        mtime_format = time.strftime("%b %d %H:%M", time.localtime(mtime))

        reset = '\033[0m'
        if os.path.isdir(path):
            color = '\033[1;94m'
        elif os.access(path, os.X_OK):
            color = '\033[1;92m'
        else:
            color = ''

        if not senf.supports_ansi_escape_codes(sys.stdout.fileno()):
            reset = color = ''

        senf.print_("%6d %13s %s%s%s" % (size, mtime_format, color,
                                         entry, reset)) 
Example 17
Project: core   Author: getavalon   File: lib.py    MIT License 6 votes vote down vote up
def which(program):
    """Locate `program` in PATH

    Arguments:
        program (str): Name of program, e.g. "python"

    """

    def is_exe(fpath):
        if os.path.isfile(fpath) and os.access(fpath, os.X_OK):
            return True
        return False

    for path in os.environ["PATH"].split(os.pathsep):
        for ext in os.getenv("PATHEXT", "").split(os.pathsep):
            fname = program + ext.lower()
            abspath = os.path.join(path.strip('"'), fname)

            if is_exe(abspath):
                return abspath

    return None 
Example 18
Project: toil-scripts   Author: BD2KGenomics   File: rnaseq_unc_tcga_versions.py    Apache License 2.0 6 votes vote down vote up
def which(program):
    import os

    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None 
Example 19
Project: toil-scripts   Author: BD2KGenomics   File: rnaseq_unc_pipeline.py    Apache License 2.0 6 votes vote down vote up
def which(program):
    import os

    def is_exe(f):
        return os.path.isfile(f) and os.access(f, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            return program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                return exe_file

    return None 
Example 20
Project: cmo   Author: mskcc   File: workflow.py    GNU General Public License v2.0 6 votes vote down vote up
def which(self, program):
        import os
        def is_exe(fpath):
            return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

        fpath, fname = os.path.split(program)
        if fpath:
            if is_exe(program):
                return program
        else:
            for path in os.environ["PATH"].split(os.pathsep):
                path = path.strip('"')
                exe_file = os.path.join(path, program)
                if is_exe(exe_file):
                    return exe_file

        return None 
Example 21
Project: fs_image   Author: facebookincubator   File: install_file.py    MIT License 5 votes vote down vote up
def _recurse_into_source(
    source_dir: Path, dest_dir: str, *,
    dir_mode: Mode, exe_mode: Mode, data_mode: Mode,
) -> Iterable[_InstallablePath]:
    'Yields paths in top-down order, making recursive copying easy.'
    yield _InstallablePath(
        source=source_dir,
        provides=ProvidesDirectory(path=dest_dir.decode()),
        mode=dir_mode,
    )
    with os.scandir(source_dir) as it:
        for e in it:
            source = source_dir / e.name
            dest = dest_dir / e.name
            if e.is_dir(follow_symlinks=False):
                yield from _recurse_into_source(
                    source, dest,
                    dir_mode=dir_mode, exe_mode=exe_mode, data_mode=data_mode,
                )
            elif e.is_file(follow_symlinks=False):
                yield _InstallablePath(
                    source=source,
                    provides=ProvidesFile(path=dest.decode()),
                    # Same `os.access` rationale as in `customize_fields`.
                    mode=exe_mode if os.access(source, os.X_OK) else data_mode,
                )
            else:
                raise RuntimeError(f'{source}: neither a file nor a directory') 
Example 22
Project: pyblish-win   Author: pyblish   File: __init__.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def exe(self):
        """The process executable as an absolute path.
        May also be an empty string.
        The return value is cached after first call.
        """
        def guess_it(fallback):
            # try to guess exe from cmdline[0] in absence of a native
            # exe representation
            cmdline = self.cmdline()
            if cmdline and hasattr(os, 'access') and hasattr(os, 'X_OK'):
                exe = cmdline[0]  # the possible exe
                # Attempt to guess only in case of an absolute path.
                # It is not safe otherwise as the process might have
                # changed cwd.
                if (os.path.isabs(exe) and
                        os.path.isfile(exe) and
                        os.access(exe, os.X_OK)):
                    return exe
            if isinstance(fallback, AccessDenied):
                raise fallback
            return fallback

        if self._exe is None:
            try:
                exe = self._proc.exe()
            except AccessDenied as err:
                return guess_it(fallback=err)
            else:
                if not exe:
                    # underlying implementation can legitimately return an
                    # empty string; if that's the case we don't want to
                    # raise AD while guessing from the cmdline
                    try:
                        exe = guess_it(fallback=exe)
                    except AccessDenied:
                        pass
                self._exe = exe
        return self._exe 
Example 23
Project: pyblish-win   Author: pyblish   File: test_uuid.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_find_mac(self):
        data = '''\

fake hwaddr
cscotun0  Link encap:UNSPEC  HWaddr 00-00-00-00-00-00-00-00-00-00-00-00-00-00-00-00
eth0      Link encap:Ethernet  HWaddr 12:34:56:78:90:ab
'''
        def mock_popen(cmd):
            return io.BytesIO(data)

        path = os.environ.get("PATH", os.defpath).split(os.pathsep)
        path.extend(('/sbin', '/usr/sbin'))
        for dir in path:
            executable = os.path.join(dir, 'ifconfig')
            if (os.path.exists(executable) and
                os.access(executable, os.F_OK | os.X_OK) and
                not os.path.isdir(executable)):
                break
        else:
            self.skipTest('requires ifconfig')

        with test_support.swap_attr(os, 'popen', mock_popen):
            mac = uuid._find_mac(
                command='ifconfig',
                args='',
                hw_identifiers=['hwaddr'],
                get_index=lambda x: x + 1,
            )
            self.assertEqual(mac, 0x1234567890ab) 
Example 24
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: grafana_plugin.py    MIT License 5 votes vote down vote up
def grafana_cli_bin(params):
    '''
    Get the grafana-cli binary path with global options.
    Raise a GrafanaCliException if the grafana-cli is not present or not in PATH

    :param params: ansible module params. Used to fill grafana-cli global params.
    '''
    program = 'grafana-cli'
    grafana_cli = None

    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    fpath, fname = os.path.split(program)
    if fpath:
        if is_exe(program):
            grafana_cli = program
    else:
        for path in os.environ["PATH"].split(os.pathsep):
            path = path.strip('"')
            exe_file = os.path.join(path, program)
            if is_exe(exe_file):
                grafana_cli = exe_file
                break

    if grafana_cli is None:
        raise GrafanaCliException('grafana-cli binary is not present or not in PATH')
    else:
        if 'grafana_plugin_url' in params and params['grafana_plugin_url']:
            grafana_cli = '{} {} {}'.format(grafana_cli, '--pluginUrl', params['grafana_plugin_url'])
        if 'grafana_plugins_dir' in params and params['grafana_plugins_dir']:
            grafana_cli = '{} {} {}'.format(grafana_cli, '--pluginsDir', params['grafana_plugins_dir'])
        if 'grafana_repo' in params and params['grafana_repo']:
            grafana_cli = '{} {} {}'.format(grafana_cli, '--repo', params['grafana_repo'])
        if 'validate_certs' in params and params['validate_certs'] is False:
            grafana_cli = '{} {}'.format(grafana_cli, '--insecure')

        return '{} {}'.format(grafana_cli, 'plugins') 
Example 25
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: git.py    MIT License 5 votes vote down vote up
def write_ssh_wrapper():
    module_dir = get_module_path()
    try:
        # make sure we have full permission to the module_dir, which
        # may not be the case if we're sudo'ing to a non-root user
        if os.access(module_dir, os.W_OK | os.R_OK | os.X_OK):
            fd, wrapper_path = tempfile.mkstemp(prefix=module_dir + '/')
        else:
            raise OSError
    except (IOError, OSError):
        fd, wrapper_path = tempfile.mkstemp()
    fh = os.fdopen(fd, 'w+b')
    template = b("""#!/bin/sh
if [ -z "$GIT_SSH_OPTS" ]; then
    BASEOPTS=""
else
    BASEOPTS=$GIT_SSH_OPTS
fi

# Let ssh fail rather than prompt
BASEOPTS="$BASEOPTS -o BatchMode=yes"

if [ -z "$GIT_KEY" ]; then
    ssh $BASEOPTS "[email protected]"
else
    ssh -i "$GIT_KEY" -o IdentitiesOnly=yes $BASEOPTS "[email protected]"
fi
""")
    fh.write(template)
    fh.close()
    st = os.stat(wrapper_path)
    os.chmod(wrapper_path, st.st_mode | stat.S_IEXEC)
    return wrapper_path 
Example 26
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: user.py    MIT License 5 votes vote down vote up
def _check_usermod_append(self):
        # check if this version of usermod can append groups

        if self.local:
            command_name = 'lusermod'
        else:
            command_name = 'usermod'

        usermod_path = self.module.get_bin_path(command_name, True)

        # for some reason, usermod --help cannot be used by non root
        # on RH/Fedora, due to lack of execute bit for others
        if not os.access(usermod_path, os.X_OK):
            return False

        cmd = [usermod_path, '--help']
        (rc, data1, data2) = self.execute_command(cmd, obey_checkmode=False)
        helpout = data1 + data2

        # check if --append exists
        lines = to_native(helpout).split('\n')
        for line in lines:
            if line.strip().startswith('-a, --append'):
                return True

        return False 
Example 27
Project: flasky   Author: RoseOu   File: firefox_binary.py    MIT License 5 votes vote down vote up
def _default_windows_location(self):
        program_files = [os.getenv("PROGRAMFILES", r"C:\Program Files"),
                         os.getenv("PROGRAMFILES(X86)", r"C:\Program Files (x86)")]
        for path in program_files:
            binary_path = os.path.join(path, r"Mozilla Firefox\firefox.exe")
            if os.access(binary_path, os.X_OK):
                return binary_path
        return "" 
Example 28
Project: flasky   Author: RoseOu   File: firefox_binary.py    MIT License 5 votes vote down vote up
def which(self, fname):
        """Returns the fully qualified path by searching Path of the given 
        name"""
        for pe in os.environ['PATH'].split(os.pathsep):
            checkname = os.path.join(pe, fname)
            if os.access(checkname, os.X_OK) and not os.path.isdir(checkname):
                return checkname
        return None 
Example 29
Project: flasky   Author: RoseOu   File: environment.py    MIT License 5 votes vote down vote up
def _which_dirs(cmd):
    result = set()
    for path in os.environ.get('PATH', '').split(os.pathsep):
        filename = os.path.join(path, cmd)
        if os.access(filename, os.X_OK):
            result.add(path)
    return result 
Example 30
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: fping.py    Apache License 2.0 5 votes vote down vote up
def check_fping(self):
        if not os.access(CONF.fping_path, os.X_OK):
            raise exc.HTTPServiceUnavailable(
                explanation=_("fping utility is not found.")) 
Example 31
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: fping.py    Apache License 2.0 5 votes vote down vote up
def check_fping(self):
        if not os.access(CONF.fping_path, os.X_OK):
            raise exc.HTTPServiceUnavailable(
                explanation=_("fping utility is not found.")) 
Example 32
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: scality.py    Apache License 2.0 5 votes vote down vote up
def _check_prerequisites(self):
        """Sanity checks before attempting to mount SOFS."""

        # config is mandatory
        config = CONF.libvirt.scality_sofs_config
        if not config:
            msg = _("Value required for 'scality_sofs_config'")
            LOG.warning(msg)
            raise exception.NovaException(msg)

        # config can be a file path or a URL, check it
        if urlparse.urlparse(config).scheme == '':
            # turn local path into URL
            config = 'file://%s' % config
        try:
            urllib.request.urlopen(config, timeout=5).close()
        except urllib.error.URLError as e:
            msg = _("Cannot access 'scality_sofs_config': %s") % e
            LOG.warning(msg)
            raise exception.NovaException(msg)

        # mount.sofs must be installed
        if not os.access('/sbin/mount.sofs', os.X_OK):
            msg = _("Cannot execute /sbin/mount.sofs")
            LOG.warning(msg)
            raise exception.NovaException(msg) 
Example 33
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: quobyte.py    Apache License 2.0 5 votes vote down vote up
def validate_volume(mnt_base):
    """Wraps execute calls for checking validity of a Quobyte volume"""
    command = ['getfattr', "-n", "quobyte.info", mnt_base]
    try:
        utils.execute(*command)
    except processutils.ProcessExecutionError as exc:
        msg = (_("The mount %(mount_path)s is not a valid"
                 " Quobyte volume. Error: %(exc)s")
               % {'mount_path': mnt_base, 'exc': exc})
        raise nova_exception.NovaException(msg)

    if not os.access(mnt_base, os.W_OK | os.X_OK):
        msg = (_LE("Volume is not writable. Please broaden the file"
                   " permissions. Mount: %s") % mnt_base)
        raise nova_exception.NovaException(msg) 
Example 34
Project: planb   Author: ossobv   File: fields.py    GNU General Public License v3.0 5 votes vote down vote up
def clean(self, value):
        value = super().clean(value)
        if not value:
            return value

        values = value.strip().split()
        if not values or values[0][0] != '/':
            raise forms.ValidationError(_(
                'Command needs to start with a /'))

        if not os.access(values[0], os.X_OK, effective_ids=True):
            raise forms.ValidationError(_(
                'Command not found or no permissions'))

        return ' '.join(values) 
Example 35
Project: face_rekognition   Author: cnidus   File: ImageShow.py    GNU General Public License v3.0 5 votes vote down vote up
def which(executable):
        path = os.environ.get("PATH")
        if not path:
            return None
        for dirname in path.split(os.pathsep):
            filename = os.path.join(dirname, executable)
            if os.path.isfile(filename) and os.access(filename, os.X_OK):
                return filename
        return None 
Example 36
Project: AshsSDK   Author: thehappydinoa   File: emrutils.py    MIT License 5 votes vote down vote up
def which(program):
    for path in os.environ["PATH"].split(os.pathsep):
        path = path.strip('"')
        exe_file = os.path.join(path, program)
        if os.path.isfile(exe_file) and os.access(exe_file, os.X_OK):
            return exe_file

    return None 
Example 37
Project: QCElemental   Author: MolSSI   File: importing.py    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 38
Project: relay-bench   Author: uwsampl   File: dashboard.py    Apache License 2.0 5 votes vote down vote up
def check_present_and_executable(subdir, filenames):
    """
    Checks that all the files in the list are present in the subdirectory
    and are executable. Returns a list of any files in the list that are
    not present or not executable.
    """
    invalid = []
    for filename in filenames:
        path = os.path.join(subdir, filename)
        if not os.path.isfile(path) or not os.access(path, os.X_OK):
            invalid.append(filename)
    return invalid 
Example 39
Project: relay-bench   Author: uwsampl   File: dashboard.py    Apache License 2.0 5 votes vote down vote up
def has_setup(experiments_dir, exp_name):
    setup_path = os.path.join(experiments_dir, exp_name, 'setup.sh')
    return os.path.isfile(setup_path) and os.access(setup_path, os.X_OK) 
Example 40
Project: mx   Author: graalvm   File: select_jdk.py    GNU General Public License v2.0 5 votes vote down vote up
def is_valid_jdk(jdk):
    """
    Determines if `jdk` looks like a valid JDK directory.

    :return: True if there's a ``java`` executable in ``jdk/bin``
    """
    java_exe = join(jdk, 'bin', 'java')
    if not exists(java_exe):
        java_exe += '.exe'
    return isfile(java_exe) and os.access(java_exe, os.X_OK) 
Example 41
Project: xia2   Author: xia2   File: Environment.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def which(pgm, debug=False):
    path = os.getenv("PATH")
    for p in path.split(os.path.pathsep):
        p = os.path.join(p, pgm)
        if debug:
            Chatter.write("Seeking %s" % p)
        if os.path.exists(p) and os.access(p, os.X_OK):
            return p 
Example 42
Project: sdn-loadbalancer   Author: AnotherKamila   File: conftest.py    MIT License 5 votes vote down vote up
def controller(request):
    """Runs our controller for each switch in the topology.

    "Our controller" means an executable called "./controller" in the test directory;
    you might want it to call something from controller/, such as:

        #!/bin/sh
        python -m controller.l3_controller $1

    """
    testdir = request.fspath.dirname  # work in the test directory
    exe     = os.path.join(testdir, './controller')

    if not os.path.exists(exe):
        raise ValueError('./controller does not exist in {}'.format(testdir))
    if not os.access(exe, os.X_OK):
        raise ValueError('./controller is not executable: in {}'.format(testdir))

    p4 = P4Obj(testdir)

    def start_ctrls():
        for s in p4.topo.get_p4switches():
            yield subprocess.Popen(
                ['./controller', s],
                cwd=testdir,
            )
    ctrls = list(start_ctrls())
    time.sleep(3)  # wait for the controller to fill out the initial tables
    for c in ctrls:
        retcode = c.poll()
        if retcode not in [None, 0]:
            raise Exception("controller exited with error status: {}".format(retcode))
    return ctrls


################### Twisted helpers ################### 
Example 43
Project: maintain   Author: kylef   File: hooks.py    BSD 2-Clause "Simplified" License 5 votes vote down vote up
def execute_hooks(self, phase, commands, version):
        if len(commands) > 0:
            logger.info('Running {} hooks'.format(phase))

            for hook in commands:
                logger.info('$ {}'.format(hook))
                subprocess.check_output(hook, shell=True, env={'VERSION': version})

        hook_file = './.maintain/hooks/{}'.format(phase)

        if os.path.exists(hook_file) and os.access(hook_file, os.X_OK):
            subprocess.check_output(hook_file, shell=True, env={'VERSION': version}) 
Example 44
Project: youku   Author: hanguokai   File: youku_upload.py    Apache License 2.0 5 votes vote down vote up
def _save_upload_state_to_file(self):
        """if create and create_file has execute, save upload state
        to file for next resume upload if current upload process is
        interrupted.
        """
        if os.access(self.file_dir, os.W_OK | os.R_OK | os.X_OK):
            save_file = self.file + '.upload'
            data = {
                'upload_token': self.upload_token,
                'upload_server_ip': self.upload_server_ip
            }
            with open(save_file, 'w') as f:
                json.dump(data, f) 
Example 45
Project: Repobot   Author: Desgard   File: server.py    MIT License 5 votes vote down vote up
def executable(path):
    """Test for executable file."""
    return os.access(path, os.X_OK) 
Example 46
Project: Repobot   Author: Desgard   File: filesystem.py    MIT License 5 votes vote down vote up
def __init__(self):
        PathCompleter.__init__(
            self,
            only_directories=False,
            min_input_len=1,
            get_paths=lambda: os.environ.get('PATH', '').split(os.pathsep),
            file_filter=lambda name: os.access(name, os.X_OK),
            expanduser=True), 
Example 47
Project: Repobot   Author: Desgard   File: utils.py    MIT License 5 votes vote down vote up
def is_executable_file(path):
    """Checks that path is an executable regular file, or a symlink towards one.

    This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``.
    """
    # follow symlinks,
    fpath = os.path.realpath(path)

    if not os.path.isfile(fpath):
        # non-files (directories, fifo, etc.)
        return False

    mode = os.stat(fpath).st_mode

    if (sys.platform.startswith('sunos')
            and os.getuid() == 0):
        # When root on Solaris, os.X_OK is True for *all* files, irregardless
        # of their executability -- instead, any permission bit of any user,
        # group, or other is fine enough.
        #
        # (This may be true for other "Unix98" OS's such as HP-UX and AIX)
        return bool(mode & (stat.S_IXUSR |
                            stat.S_IXGRP |
                            stat.S_IXOTH))

    return os.access(fpath, os.X_OK) 
Example 48
Project: osg-configure   Author: opensciencegrid   File: validation.py    Apache License 2.0 5 votes vote down vote up
def valid_executable(file_name):
    """
    Check to make sure that a file is present and a valid executable
    """
    try:
        if (not valid_file(file_name) or
                not os.access(file_name, os.X_OK)):
            return False
    except IOError:
        return False
    return True 
Example 49
Project: zun   Author: openstack   File: status.py    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 50
Project: deoplete-swift   Author: landaire   File: swift.py    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 51
Project: djing   Author: nerosketch   File: dev_types.py    The Unlicense 5 votes vote down vote up
def ex_expect(filename, params=()):
    base_dir = getattr(settings, 'BASE_DIR')
    if base_dir is not None:
        exec_file = os.path.join(base_dir, 'devapp', 'expect_scripts', filename)
        if os.path.isfile(exec_file) and os.access(path=exec_file, mode=os.X_OK):
            params = ' '.join(str(p) for p in params)
            if params:
                return os.system('%s %s' % (exec_file, params))
            else:
                return os.system(exec_file)
        else:
            raise DeviceConfigurationError(_('File %(filename)s is not exists or not executable') % {
                'filename': exec_file
            }) 
Example 52
Project: downstream-cherry-picker   Author: red-hat-storage   File: __init__.py    MIT License 5 votes vote down vote up
def ensure_hook():
    """ Ensure that the .git/hooks/prepare-commit-msg file is ready """
    hook = '.git/hooks/prepare-commit-msg'
    # https://gist.github.com/alfredodeza/252d66dbf4a5c36cfb7b1cb3c0faf445
    if not os.path.isfile(hook):
        log.warn('%s not found, downloading from Gist' % hook)
        r = requests.get(HOOK_URL)
        fh = open(hook, 'w')
        fh.write(r.text)
        fh.close()
    if not os.access(hook, os.X_OK):
        st = os.stat(hook)
        os.chmod(hook, st.st_mode | stat.S_IXUSR | stat.S_IXGRP | stat.S_IXOTH) 
Example 53
Project: recipes-py   Author: luci   File: recipes.py    Apache License 2.0 5 votes vote down vote up
def _is_executable(path):
  return os.path.isfile(path) and os.access(path, os.X_OK)


# TODO: Use shutil.which once we switch to Python3. 
Example 54
Project: recipes-py   Author: luci   File: subproc.py    Apache License 2.0 5 votes vote down vote up
def _is_executable_file(path):
    """Returns True iff `path` is:

      * A file
      * User has +x access to it
    """
    return os.path.isfile(path) and os.access(path, os.X_OK) 
Example 55
Project: Arachis   Author: Kinggerm   File: run_pypmag.py    GNU General Public License v3.0 5 votes vote down vote up
def executable(test_this):
    return True if os.access(test_this, os.X_OK) or getstatusoutput(test_this)[0] != dead_code else False 
Example 56
Project: DRCOG_Urbansim   Author: apdjustino   File: path.py    GNU Affero General Public License v3.0 5 votes vote down vote up
def access(self, mode):
            """ Return true if current user has access to this path.

            mode - One of the constants os.F_OK, os.R_OK, os.W_OK, os.X_OK
            """
            return os.access(self, mode) 
Example 57
Project: pysswords   Author: marcwebbie   File: utils.py    MIT License 5 votes vote down vote up
def which(program):
    """Mimics behavior of UNIX which command. """
    # Add .exe program extension for windows support
    try:
        return shutil.which(program)
    except AttributeError:
        if os.name == "nt" and not program.endswith(".exe"):
            program += ".exe"

        for envdir in os.environ["PATH"].split(os.pathsep):
            program_path = os.path.join(envdir, program)
            if os.path.isfile(program_path) and os.access(
                    program_path, os.X_OK):
                return program_path 
Example 58
Project: honeybee   Author: ladybug-tools   File: config.py    GNU General Public License v3.0 5 votes vote down vote up
def _which(program):
        """Find executable programs.

        Args:
            program: Full file name for the program (e.g. rad.exe)

        Returns:
            File directory and full path to program in case of success.
            None, None in case of failure.
        """
        def is_exe(fpath):
            # Make sure it's not part of Dive installation as DIVA doesn't
            # follow the standard structure folder for Daysim and Radiance
            if os.name == 'nt' and fpath.upper().find("DIVA"):
                return False

            # Return true if file exists and is executable
            return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

        # check for the file in all path in environment
        for path in os.environ["PATH"].split(os.pathsep):
            # strip "" from Windows path
            exe_file = os.path.join(path.strip('"'), program)
            if is_exe(exe_file):
                return path, exe_file

        # couldn't find it! return None :|
        return None, None 
Example 59
Project: Android-Debug-Keyboard   Author: mocobk   File: filesystem.py    GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        PathCompleter.__init__(
            self,
            only_directories=False,
            min_input_len=1,
            get_paths=lambda: os.environ.get('PATH', '').split(os.pathsep),
            file_filter=lambda name: os.access(name, os.X_OK),
            expanduser=True), 
Example 60
Project: pylxd   Author: lxc   File: busybox.py    Apache License 2.0 5 votes vote down vote up
def find_on_path(command):
    """Is command on the executable search path?"""

    if 'PATH' not in os.environ:
        return False
    path = os.environ['PATH']
    for element in path.split(os.pathsep):
        if not element:
            continue
        filename = os.path.join(element, command)
        if os.path.isfile(filename) and os.access(filename, os.X_OK):
            return True
    return False 
Example 61
Project: pylxd   Author: lxc   File: busybox.py    Apache License 2.0 5 votes vote down vote up
def find_on_path(command):
    """Is command on the executable search path?"""

    if 'PATH' not in os.environ:
        return False
    path = os.environ['PATH']
    for element in path.split(os.pathsep):
        if not element:
            continue
        filename = os.path.join(element, command)
        if os.path.isfile(filename) and os.access(filename, os.X_OK):
            return True
    return False 
Example 62
Project: Flask_Blog   Author: sugarguo   File: environment.py    GNU General Public License v3.0 5 votes vote down vote up
def _which_dirs(cmd):
    result = set()
    for path in os.environ.get('PATH', '').split(os.pathsep):
        filename = os.path.join(path, cmd)
        if os.access(filename, os.X_OK):
            result.add(path)
    return result 
Example 63
Project: NiujiaoDebugger   Author: MrSrc   File: server.py    GNU General Public License v3.0 5 votes vote down vote up
def executable(path):
    """Test for executable file."""
    return os.access(path, os.X_OK) 
Example 64
Project: base16-builder-python   Author: InspectorMustache   File: builder.py    MIT License 5 votes vote down vote up
def build(templates=None, schemes=None, base_output_dir=None, verbose=False):
    """Main build function to initiate building process."""
    template_dirs = templates or get_template_dirs()
    scheme_files = get_scheme_files(schemes)
    base_output_dir = base_output_dir or rel_to_cwd("output")

    # raise LookupError if there is not at least one template or scheme
    # to work with
    if not template_dirs or not scheme_files:
        raise LookupError

    # raise PermissionError if user has no write acces for $base_output_dir
    try:
        os.makedirs(base_output_dir)
    except FileExistsError:
        pass

    if not os.access(base_output_dir, os.W_OK | os.X_OK):
        raise PermissionError

    templates = [TemplateGroup(path) for path in template_dirs]

    job_options = JobOptions(
        base_output_dir=base_output_dir, templates=templates, verbose=verbose
    )

    with compat_event_loop() as event_loop:
        results = event_loop.run_until_complete(
            build_scheduler(scheme_files, job_options)
        )

    print("Finished building process.")
    return all(results) 
Example 65
Project: Health-Checker   Author: KriAga   File: firefox_binary.py    MIT License 5 votes vote down vote up
def _default_windows_location(self):
        program_files = [os.getenv("PROGRAMFILES", r"C:\Program Files"),
                         os.getenv("PROGRAMFILES(X86)", r"C:\Program Files (x86)")]
        for path in program_files:
            binary_path = os.path.join(path, r"Mozilla Firefox\firefox.exe")
            if os.access(binary_path, os.X_OK):
                return binary_path
        return "" 
Example 66
Project: Health-Checker   Author: KriAga   File: firefox_binary.py    MIT License 5 votes vote down vote up
def which(self, fname):
        """Returns the fully qualified path by searching Path of the given
        name"""
        for pe in os.environ['PATH'].split(os.pathsep):
            checkname = os.path.join(pe, fname)
            if os.access(checkname, os.X_OK) and not os.path.isdir(checkname):
                return checkname
        return None 
Example 67
Project: cs-script-sublime   Author: oleg-shilo   File: utils.py    MIT License 5 votes vote down vote up
def get():
        if TerminalSelector.default:
            return TerminalSelector.default

        default = None

        if sys.platform == 'darwin':
            package_dir = os.path.join(sublime.packages_path(), "cs-script")
            default = os.path.join(package_dir, 'Terminal.sh')
            if not os.access(default, os.X_OK):
                os.chmod(default, 0o755)

        else:
            ps = 'ps -eo comm | grep -E "gnome-session|ksmserver|' + \
                'xfce4-session|lxsession|mate-panel|cinnamon-sessio" | grep -v grep'
            wm = [x.replace("\n", '') for x in os.popen(ps)]
            if wm:
                if 'gnome-session' in wm[0] or wm[0] == 'cinnamon-sessio':
                    default = 'gnome-terminal'
                elif wm[0] == 'xfce4-session':
                    default = 'xfce4-terminal'
                elif wm[0] == 'ksmserver':
                    default = 'konsole'
                elif wm[0] == 'lxsession':
                    default = 'lxterminal'
                elif wm[0] == 'mate-panel':
                    default = 'mate-terminal'
            if not default:
                default = 'xterm'

        TerminalSelector.default = default
        return default
# ----------------- 
Example 68
Project: sphinx-javalink   Author: bluekeyes   File: __init__.py    MIT License 5 votes vote down vote up
def _find_java_binary():
    path = os.environ.get('PATH', os.defpath)

    exts = os.environ.get('PATHEXT', '')
    java_names = ['java' + ext for ext in exts.split(os.pathsep)]

    for p in path.split(os.pathsep):
        p = p.strip('"')
        for name in java_names:
            java = os.path.join(p, name)
            if os.path.isfile(java) and os.access(java, os.X_OK):
                return java

    raise ExtensionError("Could not find 'java' binary in PATH") 
Example 69
Project: fs_image   Author: facebookincubator   File: install_file.py    MIT License 4 votes vote down vote up
def customize_fields(kwargs):  # noqa: B902
        coerce_path_field_normal_relative(kwargs, 'dest')
        customize_stat_options(kwargs, default_mode=None)  # Defaulted later

        source = kwargs['source']
        dest = kwargs['dest']

        popped_args = ['mode', 'exe_mode', 'data_mode', 'dir_mode']
        mode, dir_mode, exe_mode, data_mode = (
            kwargs.pop(a) for a in popped_args
        )

        st_source = os.stat(source, follow_symlinks=False)
        if stat.S_ISDIR(st_source.st_mode):
            assert mode is None, f'Cannot use `mode` for directory sources.'
            kwargs['paths'] = tuple(_recurse_into_source(
                Path(source), Path(dest),
                dir_mode=dir_mode or _DIR_MODE,
                exe_mode=exe_mode or _EXE_MODE,
                data_mode=data_mode or _DATA_MODE,
            ))
        elif stat.S_ISREG(st_source.st_mode):
            assert {dir_mode, exe_mode, data_mode} == {None}, \
                'Cannot use `{dir,exe,data}_mode` for file sources.'
            if mode is None:
                # This tests whether the build repo user can execute the
                # file.  This is a very natural test for build artifacts,
                # and files in the repo.  Note that this can be affected if
                # the ambient umask is pathological, which is why
                # `compiler.py` checks the umask.
                mode = _EXE_MODE if os.access(source, os.X_OK) else _DATA_MODE
            kwargs['paths'] = (_InstallablePath(
                source=source,
                provides=ProvidesFile(path=dest),
                mode=mode,
            ),)
        else:
            raise RuntimeError(
                f'{source} must be a regular file or directory, got {st_source}'
            )

        # These must be set for `enriched_namedtuple`.  Set them last to
        # prevent accidental access.
        for a in popped_args:
            assert a not in kwargs, f'{a} was set in {kwargs}'
            kwargs[a] = None 
Example 70
Project: sic   Author: Yanixos   File: shutil.py    GNU General Public License v3.0 4 votes vote down vote up
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
    """Given a command, mode, and a PATH string, return the path which
    conforms to the given mode on the PATH, or None if there is no such
    file.

    `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
    of os.environ.get("PATH"), or can be overridden with a custom search
    path.

    """
    # Check that a given file can be accessed with the correct mode.
    # Additionally check that `file` is not a directory, as on Windows
    # directories pass the os.access check.
    def _access_check(fn, mode):
        return (os.path.exists(fn) and os.access(fn, mode)
                and not os.path.isdir(fn))

    # If we're given a path with a directory part, look it up directly rather
    # than referring to PATH directories. This includes checking relative to the
    # current directory, e.g. ./script
    if os.path.dirname(cmd):
        if _access_check(cmd, mode):
            return cmd
        return None

    if path is None:
        path = os.environ.get("PATH", os.defpath)
    if not path:
        return None
    path = path.split(os.pathsep)

    if sys.platform == "win32":
        # The current directory takes precedence on Windows.
        if not os.curdir in path:
            path.insert(0, os.curdir)

        # PATHEXT is necessary to check on Windows.
        pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
        # See if the given file matches any of the expected path extensions.
        # This will allow us to short circuit when given "python.exe".
        # If it does match, only test that one, otherwise we have to try
        # others.
        if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
            files = [cmd]
        else:
            files = [cmd + ext for ext in pathext]
    else:
        # On other platforms you don't have things like PATHEXT to tell you
        # what file suffixes are executable, so just pass on cmd as-is.
        files = [cmd]

    seen = set()
    for dir in path:
        normdir = os.path.normcase(dir)
        if not normdir in seen:
            seen.add(normdir)
            for thefile in files:
                name = os.path.join(dir, thefile)
                if _access_check(name, mode):
                    return name
    return None 
Example 71
Project: lichess-bot   Author: ShailChoksi   File: config.py    GNU Affero General Public License v3.0 4 votes vote down vote up
def load_config(config_file):
    with open(config_file) as stream:
        try:
            CONFIG = yaml.load(stream)
        except Exception as e:
            print("There appears to be a syntax problem with your config.yml")
            raise e

        #[section, type, error message]
        sections = [["token", str, "Section `token` must be a string wrapped in quotes."],
                    ["url", str, "Section `url` must be a string wrapped in quotes."],
                    ["engine", dict, "Section `engine` must be a dictionary with indented keys followed by colons.."],
                    ["challenge", dict, "Section `challenge` must be a dictionary with indented keys followed by colons.."]]
        for section in sections:
            if section[0] not in CONFIG:
                raise Exception("Your config.yml does not have required section `{}`.".format(section[0]))
            elif not isinstance(CONFIG[section[0]], section[1]):
                raise Exception(section[2])

        engine_sections = [["dir", str, "´dir´ must be a string wrapped in quotes."],
                           ["name", str, "´name´ must be a string wrapped in quotes."]]
        for subsection in engine_sections:
            if subsection[0] not in CONFIG["engine"]:
                raise Exception("Your config.yml does not have required `engine` subsection `{}`.".format(subsection))
            if not isinstance(CONFIG["engine"][subsection[0]], subsection[1]):
                raise Exception("´engine´ subsection {}".format(subsection[2]))

        if CONFIG["token"] == "xxxxxxxxxxxxxxxx":
            raise Exception("Your config.yml has the default Lichess API token. This is probably wrong.")

        if not os.path.isdir(CONFIG["engine"]["dir"]):
            raise Exception("Your engine directory `{}` is not a directory.")

        engine = os.path.join(CONFIG["engine"]["dir"], CONFIG["engine"]["name"])

        if not os.path.isfile(engine):
            raise Exception("The engine %s file does not exist." % engine)

        if not os.access(engine, os.X_OK):
            raise Exception("The engine %s doesn't have execute (x) permission. Try: chmod +x %s" % (engine, engine))

    return CONFIG 
Example 72
Project: mimic   Author: googlearchive   File: target_env_test.py    Apache License 2.0 4 votes vote down vote up
def testAccess(self):
    self._tree.SetFile('foo.txt', 'abc')
    self._tree.SetFile('d/bar.txt', 'def')
    self._tree.SetFile('static/index.html', 'static html')
    self._tree.SetFile('stylesheets/index.css', 'static css')
    self.assertTrue(os.access('foo.txt', os.F_OK))
    self.assertTrue(os.access('foo.txt', os.R_OK))
    self.assertFalse(os.access('foo.txt', os.W_OK))
    self.assertFalse(os.access('foo.txt', os.X_OK))
    self.assertFalse(os.access('foo.txt', os.R_OK | os.W_OK))
    self.assertTrue(os.access('/target/foo.txt', os.F_OK))
    self.assertFalse(os.access('bar.txt', os.F_OK))
    self.assertFalse(os.access('/target/bar.txt', os.F_OK))
    # directories
    self.assertTrue(os.access('/target', os.F_OK))
    self.assertTrue(os.access('/target/d', os.F_OK))
    self.assertTrue(os.access('d', os.F_OK))
    self.assertFalse(os.access('/target/f', os.F_OK))
    self.assertTrue(os.access('d', os.R_OK))
    self.assertTrue(os.access('d', os.X_OK))
    self.assertFalse(os.access('d', os.R_OK | os.W_OK))
    self.assertFalse(os.access('d', os.W_OK))
    # check external files
    self.assertTrue(os.access(__file__, os.F_OK))
    self.assertFalse(os.access('not_a_file', os.F_OK))
    # check static files
    # In production, whether or not a folder in a static_files handler is
    # accessible to a script file depends on if all the files in the folder are
    # matched by the handler, in which case the folder isn't uploaded, and thus
    # isn't accessible to script. We don't check for this, so the folder in
    # a static_files handler is always available to script. So, for example,
    # this won't pass: self.assertFalse(os.access('static', os.F_OK))
    self.assertFalse(os.access('static/index.html', os.F_OK))
    self.assertFalse(os.access('stylesheets/index.css', os.F_OK))
    self.assertFalse(os.access('stylesheets', os.F_OK))
    self.assertFalse(os.access('stylesheets_other', os.F_OK))
    # check skipped files
    self.assertFalse(os.access('README.txt', os.F_OK))
    self.assertFalse(os.access('/target/README.txt', os.F_OK))
    self.assertFalse(os.access('skip_folder', os.F_OK))
    self.assertFalse(os.access('/target/skip_folder', os.F_OK))
    self.assertFalse(os.access('/target/skip_folder/file', os.F_OK)) 
Example 73
Project: colorguard   Author: mechaphish   File: colorguard.py    BSD 2-Clause "Simplified" License 4 votes vote down vote up
def __init__(self, binary, payload):
        """
        :param binary: path to the binary which is suspect of leaking
        :param payload: concrete input string to feed to the binary
        """

        self.binary = binary
        self.payload = payload

        if not os.access(self.binary, os.X_OK):
            raise ValueError("\"%s\" binary does not exist or is not executable" % self.binary)

        # will be set by causes_leak
        self._leak_path = None

        self._runner = tracer.QEMURunner(binary=binary, input=payload)

        # load the binary
        self.project = angr.Project(binary)
        self.project.simos.syscall_library.update(angr.SIM_LIBRARIES['cgcabi_tracer'])

        # set up the state for analysis
        remove_options = {angr.options.SUPPORT_FLOATING_POINT}
        add_options = angr.options.unicorn | {
                angr.options.CGC_NO_SYMBOLIC_RECEIVE_LENGTH,
                angr.options.UNICORN_THRESHOLD_CONCRETIZATION,
                angr.options.REPLACEMENT_SOLVER }
        state = self.project.factory.full_init_state(remove_options=remove_options, add_options=add_options)

        # Make our own special posix
        state.register_plugin('posix', SimSystemPosix(
            stdin=SimFileStream('stdin', content=payload),
            stdout=SimFileStream('stdout'),
            stderr=SimFileStream('stderr')))

        # Create the preconstrainer plugin
        state.register_plugin('preconstrainer', SimStatePreconstrainer())
        state.preconstrainer.preconstrain_flag_page(self._runner.magic)

        # Set up zen
        ZenPlugin.prep_tracer(state)

        # Make the simulation manager
        self._simgr = self.project.factory.simulation_manager(state, save_unsat=True, hierarchy=False, save_unconstrained=self._runner.crash_mode)
        self._t = angr.exploration_techniques.Tracer(trace=self._runner.trace, resiliency=False)
        self._simgr.use_technique(self._t)
        self._simgr.use_technique(angr.exploration_techniques.Oppologist())

        # will be overwritten by _concrete_difference if the input was filtered
        # this attributed is used exclusively for testing at the moment
        self._no_concrete_difference = not self._concrete_difference()

        self.leak_ast = None 
Example 74
Project: calmjs   Author: calmjs   File: utils.py    GNU General Public License v2.0 4 votes vote down vote up
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
    """
    Given cmd, check where it is on PATH.

    Loosely based on the version in python 3.3.
    """

    if os.path.dirname(cmd):
        if os.path.isfile(cmd) and os.access(cmd, mode):
            return cmd

    if path is None:
        path = os.environ.get('PATH', defpath)
    if not path:
        return None

    paths = path.split(pathsep)

    if sys.platform == 'win32':
        # oh boy
        if curdir not in paths:
            paths = [curdir] + paths

        # also need to check the fileexts...
        pathext = os.environ.get('PATHEXT', '').split(pathsep)

        if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
            files = [cmd]
        else:
            files = [cmd + ext for ext in pathext]
    else:
        # sanity
        files = [cmd]

    seen = set()
    for p in paths:
        normpath = normcase(p)
        if normpath in seen:
            continue
        seen.add(normpath)
        for f in files:
            fn = os.path.join(p, f)
            if os.path.isfile(fn) and os.access(fn, mode):
                return fn

    return None 
Example 75
Project: EXOSIMS   Author: dsavransky   File: get_dirs.py    BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def get_home_dir():
    """
    Finds the Home directory for the system.

    Returns:
        homedir (str):
            Path to Home directory
    """

    # POSIX system
    if os.name == 'posix':
        if 'HOME' in os.environ:
            homedir = os.environ['HOME']
        else:
            raise OSError('Could not find POSIX home directory')
    # Windows system
    elif os.name == 'nt':
        # msys shell
        if 'MSYSTEM' in os.environ and os.environ.get('HOME'):
            homedir = os.environ['HOME']
        # network home
        elif 'HOMESHARE' in os.environ:
            homedir = os.environ['HOMESHARE']
        # local home
        elif 'HOMEDRIVE' in os.environ and 'HOMEPATH' in os.environ:
            homedir = os.path.join(os.environ['HOMEDRIVE'],os.environ['HOMEPATH'])
        # user profile?
        elif 'USERPROFILE' in os.environ:
            homedir = os.path.join(os.environ['USERPROFILE'])
        # something else?
        else:
            try:
                import winreg as wreg
                shell_folders = r'Software\Microsoft\Windows\CurrentVersion\Explorer\Shell Folders'
                key = wreg.OpenKey(wreg.HKEY_CURRENT_USER, shell_folders)
                homedir = wreg.QueryValueEx(key, 'Personal')[0]
                key.Close()
            except Exception:
                # try home before giving up
                if 'HOME' in os.environ:
                    homedir = os.environ['HOME']
                else:
                    raise OSError('Could not find Windows home directory')
    else:
        # some other platform? try HOME to see if it works
        if 'HOME' in os.environ:
            homedir = os.environ['HOME']
        else:
            raise OSError('Could not find home directory on your platform')

    assert os.path.isdir(homedir) and os.access(homedir, os.R_OK|os.W_OK|os.X_OK),\
            "Identified %s as home directory, but it does not exist or is not accessible/writeable"%homedir

    return homedir 
Example 76
Project: jawfish   Author: war-and-code   File: shutil.py    MIT License 4 votes vote down vote up
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
    """Given a command, mode, and a PATH string, return the path which
    conforms to the given mode on the PATH, or None if there is no such
    file.

    `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
    of os.environ.get("PATH"), or can be overridden with a custom search
    path.

    """
    # Check that a given file can be accessed with the correct mode.
    # Additionally check that `file` is not a directory, as on Windows
    # directories pass the os.access check.
    def _access_check(fn, mode):
        return (os.path.exists(fn) and os.access(fn, mode)
                and not os.path.isdir(fn))

    # If we're given a path with a directory part, look it up directly rather
    # than referring to PATH directories. This includes checking relative to the
    # current directory, e.g. ./script
    if os.path.dirname(cmd):
        if _access_check(cmd, mode):
            return cmd
        return None

    if path is None:
        path = os.environ.get("PATH", os.defpath)
    if not path:
        return None
    path = path.split(os.pathsep)

    if sys.platform == "win32":
        # The current directory takes precedence on Windows.
        if not os.curdir in path:
            path.insert(0, os.curdir)

        # PATHEXT is necessary to check on Windows.
        pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
        # See if the given file matches any of the expected path extensions.
        # This will allow us to short circuit when given "python.exe".
        # If it does match, only test that one, otherwise we have to try
        # others.
        if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
            files = [cmd]
        else:
            files = [cmd + ext for ext in pathext]
    else:
        # On other platforms you don't have things like PATHEXT to tell you
        # what file suffixes are executable, so just pass on cmd as-is.
        files = [cmd]

    seen = set()
    for dir in path:
        normdir = os.path.normcase(dir)
        if not normdir in seen:
            seen.add(normdir)
            for thefile in files:
                name = os.path.join(dir, thefile)
                if _access_check(name, mode):
                    return name
    return None 
Example 77
Project: Repobot   Author: Desgard   File: util.py    MIT License 4 votes vote down vote up
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
        """Given a command, mode, and a PATH string, return the path which
        conforms to the given mode on the PATH, or None if there is no such
        file.
    
        `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
        of os.environ.get("PATH"), or can be overridden with a custom search
        path.
    
        """
        # Check that a given file can be accessed with the correct mode.
        # Additionally check that `file` is not a directory, as on Windows
        # directories pass the os.access check.
        def _access_check(fn, mode):
            return (os.path.exists(fn) and os.access(fn, mode)
                    and not os.path.isdir(fn))
    
        # If we're given a path with a directory part, look it up directly rather
        # than referring to PATH directories. This includes checking relative to the
        # current directory, e.g. ./script
        if os.path.dirname(cmd):
            if _access_check(cmd, mode):
                return cmd
            return None
    
        if path is None:
            path = os.environ.get("PATH", os.defpath)
        if not path:
            return None
        path = path.split(os.pathsep)
    
        if sys.platform == "win32":
            # The current directory takes precedence on Windows.
            if not os.curdir in path:
                path.insert(0, os.curdir)
    
            # PATHEXT is necessary to check on Windows.
            pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
            # See if the given file matches any of the expected path extensions.
            # This will allow us to short circuit when given "python.exe".
            # If it does match, only test that one, otherwise we have to try
            # others.
            if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
                files = [cmd]
            else:
                files = [cmd + ext for ext in pathext]
        else:
            # On other platforms you don't have things like PATHEXT to tell you
            # what file suffixes are executable, so just pass on cmd as-is.
            files = [cmd]
    
        seen = set()
        for dir in path:
            normdir = os.path.normcase(dir)
            if not normdir in seen:
                seen.add(normdir)
                for thefile in files:
                    name = os.path.join(dir, thefile)
                    if _access_check(name, mode):
                        return name
        return None 
Example 78
Project: LaserTOF   Author: kyleuckert   File: exec_command.py    MIT License 4 votes vote down vote up
def find_executable(exe, path=None, _cache={}):
    """Return full path of a executable or None.

    Symbolic links are not followed.
    """
    key = exe, path
    try:
        return _cache[key]
    except KeyError:
        pass
    log.debug('find_executable(%r)' % exe)
    orig_exe = exe

    if path is None:
        path = os.environ.get('PATH', os.defpath)
    if os.name=='posix':
        realpath = os.path.realpath
    else:
        realpath = lambda a:a

    if exe.startswith('"'):
        exe = exe[1:-1]

    suffixes = ['']
    if os.name in ['nt', 'dos', 'os2']:
        fn, ext = os.path.splitext(exe)
        extra_suffixes = ['.exe', '.com', '.bat']
        if ext.lower() not in extra_suffixes:
            suffixes = extra_suffixes

    if os.path.isabs(exe):
        paths = ['']
    else:
        paths = [ os.path.abspath(p) for p in path.split(os.pathsep) ]

    for path in paths:
        fn = os.path.join(path, exe)
        for s in suffixes:
            f_ext = fn+s
            if not os.path.islink(f_ext):
                f_ext = realpath(f_ext)
            if os.path.isfile(f_ext) and os.access(f_ext, os.X_OK):
                log.info('Found executable %s' % f_ext)
                _cache[key] = f_ext
                return f_ext

    log.warn('Could not locate executable %s' % orig_exe)
    return None

############################################################ 
Example 79
Project: NiujiaoDebugger   Author: MrSrc   File: shutil.py    GNU General Public License v3.0 4 votes vote down vote up
def which(cmd, mode=os.F_OK | os.X_OK, path=None):
    """Given a command, mode, and a PATH string, return the path which
    conforms to the given mode on the PATH, or None if there is no such
    file.

    `mode` defaults to os.F_OK | os.X_OK. `path` defaults to the result
    of os.environ.get("PATH"), or can be overridden with a custom search
    path.

    """
    # Check that a given file can be accessed with the correct mode.
    # Additionally check that `file` is not a directory, as on Windows
    # directories pass the os.access check.
    def _access_check(fn, mode):
        return (os.path.exists(fn) and os.access(fn, mode)
                and not os.path.isdir(fn))

    # If we're given a path with a directory part, look it up directly rather
    # than referring to PATH directories. This includes checking relative to the
    # current directory, e.g. ./script
    if os.path.dirname(cmd):
        if _access_check(cmd, mode):
            return cmd
        return None

    if path is None:
        path = os.environ.get("PATH", os.defpath)
    if not path:
        return None
    path = path.split(os.pathsep)

    if sys.platform == "win32":
        # The current directory takes precedence on Windows.
        if not os.curdir in path:
            path.insert(0, os.curdir)

        # PATHEXT is necessary to check on Windows.
        pathext = os.environ.get("PATHEXT", "").split(os.pathsep)
        # See if the given file matches any of the expected path extensions.
        # This will allow us to short circuit when given "python.exe".
        # If it does match, only test that one, otherwise we have to try
        # others.
        if any(cmd.lower().endswith(ext.lower()) for ext in pathext):
            files = [cmd]
        else:
            files = [cmd + ext for ext in pathext]
    else:
        # On other platforms you don't have things like PATHEXT to tell you
        # what file suffixes are executable, so just pass on cmd as-is.
        files = [cmd]

    seen = set()
    for dir in path:
        normdir = os.path.normcase(dir)
        if not normdir in seen:
            seen.add(normdir)
            for thefile in files:
                name = os.path.join(dir, thefile)
                if _access_check(name, mode):
                    return name
    return None 
Example 80
Project: libvcs   Author: vcs-python   File: util.py    MIT License 4 votes vote down vote up
def which(
    exe=None, default_paths=['/bin', '/sbin', '/usr/bin', '/usr/sbin', '/usr/local/bin']
):
    """Return path of bin. Python clone of /usr/bin/which.

    from salt.util - https://www.github.com/saltstack/salt - license apache

    :param exe: Application to search PATHs for.
    :type exe: str
    :param default_path: Application to search PATHs for.
    :type default_path: list
    :rtype: str
    """

    def _is_executable_file_or_link(exe):
        # check for os.X_OK doesn't suffice because directory may executable
        return os.access(exe, os.X_OK) and (os.path.isfile(exe) or os.path.islink(exe))

    if _is_executable_file_or_link(exe):
        # executable in cwd or fullpath
        return exe

    # Enhance POSIX path for the reliability at some environments, when
    # $PATH is changing. This also keeps order, where 'first came, first
    # win' for cases to find optional alternatives
    search_path = (
        os.environ.get('PATH') and os.environ['PATH'].split(os.pathsep) or list()
    )
    for default_path in default_paths:
        if default_path not in search_path:
            search_path.append(default_path)
    os.environ['PATH'] = os.pathsep.join(search_path)
    for path in search_path:
        full_path = os.path.join(path, exe)
        if _is_executable_file_or_link(full_path):
            return full_path
    logger.info(
        '\'{0}\' could not be found in the following search path: '
        '\'{1}\''.format(exe, search_path)
    )

    return None