Python os.X_OK Examples

The following are 30 code examples of os.X_OK(). 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 also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: install_solc.py    From py-solc with MIT License 7 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 #2
Source File: os_utils.py    From godot-mono-builds with MIT License 6 votes vote down vote up
def find_executable(name) -> str:
    is_windows = os.name == 'nt'
    windows_exts = os.environ['PATHEXT'].split(ENV_PATH_SEP) if is_windows else None
    path_dirs = os.environ['PATH'].split(ENV_PATH_SEP)

    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 #3
Source File: utilities.py    From RoboGif with Apache License 2.0 6 votes vote down vote up
def which(program):

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

    fpath, _ = 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 #4
Source File: lib.py    From core with 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 #5
Source File: util.py    From cf-mendix-buildpack with Apache License 2.0 6 votes vote down vote up
def run_post_unpack_hook(post_unpack_hook):
    if os.path.isfile(post_unpack_hook):
        if os.access(post_unpack_hook, os.X_OK):
            logger.info("Running post-unpack-hook: %s" % post_unpack_hook)
            retcode = subprocess.call((post_unpack_hook,))
            if retcode != 0:
                logger.error(
                    "The post-unpack-hook returned a "
                    "non-zero exit code: %d" % retcode
                )
        else:
            logger.error(
                "post-unpack-hook script %s is not "
                "executable." % post_unpack_hook
            )
    else:
        logger.error(
            "post-unpack-hook script %s does not exist." % post_unpack_hook
        ) 
Example #6
Source File: rnaseq_unc_tcga_versions.py    From toil-scripts with 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 #7
Source File: startup.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def which(program):
	"""
	Examine the ``PATH`` environment variable to determine the location for the
	specified program. If it can not be found None is returned. This is
	fundamentally similar to the Unix utility of the same name.

	:param str program: The name of the program to search for.
	:return: The absolute path to the program if found.
	:rtype: str
	"""
	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 #8
Source File: install.py    From py-solc with 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 #9
Source File: filesystem.py    From py-solc with 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 #10
Source File: letsencrypt.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _sync_hostnames(unified_directory):
	directory = os.path.join(unified_directory, 'etc', 'live')
	if not os.path.isdir(directory):
		logger.warning('can not enumerate available letsencrypt data (directory not found)')
		return
	if not os.access(directory, os.R_OK | os.X_OK):
		logger.warning('can not enumerate available letsencrypt data (invalid permissions)')
		return
	for subdirectory in os.listdir(directory):
		match = _HOSTNAME_DIRECTORY_REGEX.match(subdirectory)
		if match is None:
			continue
		hostname = match.group('hostname')
		if hostname in _sni_hostnames:
			continue
		certfile, keyfile = _get_files(directory, match.group('hostname'))
		if not (certfile and keyfile):
			continue
		set_sni_hostname(hostname, certfile, keyfile) 
Example #11
Source File: letsencrypt.py    From king-phisher with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_certbot_bin_path(config=None):
	"""
	Get the path to Let's Encrypt's ``certbot`` command line utility. If the
	path is found, it is verified to be both a file and executable. If the
	path verification fails, ``None`` is returned.

	.. versionadded:: 1.14.0

	:param config: Configuration to retrieve settings from.
	:type config: :py:class:`smoke_zephyr.configuration.Configuration`
	:return: The path to the certbot binary.
	:rtype: str
	"""
	if config:
		letsencrypt_config = config.get_if_exists('server.letsencrypt', {})
	else:
		letsencrypt_config = {}
	bin_path = letsencrypt_config.get('certbot_path') or startup.which('certbot')
	if bin_path is None:
		return None
	if not os.path.isfile(bin_path):
		return None
	if not os.access(bin_path, os.R_OK | os.X_OK):
		return None
	return bin_path 
Example #12
Source File: rnaseq_unc_pipeline.py    From toil-scripts with 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 #13
Source File: cache.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def GetCacheDir(session):
    """Returns the path of a usable cache directory."""
    cache_dir = session.GetParameter("cache_dir")
    if cache_dir == None:
        return cache_dir

    cache_dir = os.path.expandvars(cache_dir)

    if not cache_dir:
        raise io_manager.IOManagerError(
            "Local profile cache is not configured - "
            "add a cache_dir parameter to ~/.rekallrc.")

    # Cache dir may be specified relative to the home directory.
    cache_dir = os.path.join(config.GetHomeDir(session), cache_dir)

    if not os.access(cache_dir, os.F_OK | os.R_OK | os.W_OK | os.X_OK):
        try:
            os.makedirs(cache_dir)
        except (IOError, OSError):
            raise io_manager.IOManagerError(
                "Unable to create or access cache directory %s" % cache_dir)

    return cache_dir 
Example #14
Source File: __init__.py    From ros2cli with Apache License 2.0 6 votes vote down vote up
def get_executable_paths(*, package_name):
    prefix_path = get_prefix_path(package_name)
    if prefix_path is None:
        raise PackageNotFound(package_name)
    base_path = os.path.join(prefix_path, 'lib', package_name)
    executable_paths = []
    for dirpath, dirnames, filenames in os.walk(base_path):
        # ignore folder starting with .
        dirnames[:] = [d for d in dirnames if d[0] not in ['.']]
        dirnames.sort()
        # select executable files
        for filename in sorted(filenames):
            path = os.path.join(dirpath, filename)
            if os.access(path, os.X_OK):
                executable_paths.append(path)
    return executable_paths 
Example #15
Source File: __init__.py    From TFFRCNN with 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 #16
Source File: cache.py    From aumfor with GNU General Public License v3.0 6 votes vote down vote up
def dump(self, url, payload):
        # TODO: Ensure a better check for ieee1394/non-cachable address spaces than a bad URL
        try:
            filename = self.filename(url)
        except exceptions.CacheRelativeURLException:
            debug.debug("NOT Dumping url {0} - relative URLs are not yet supported".format(url))
            return

        ## Check that the directory exists
        directory = os.path.dirname(filename)
        if not os.access(directory, os.R_OK | os.W_OK | os.X_OK):
            os.makedirs(directory)

        ## Ensure that the payload is flattened - i.e. all generators are converted to lists for pickling
        try:
            data = pickle.dumps(payload)
            debug.debug("Dumping filename {0}".format(filename))
            fd = open(filename, 'w')
            fd.write(data)
            fd.close()
        except (pickle.PickleError, TypeError):
            # Do nothing if the pickle fails
            debug.debug("NOT Dumping filename {0} - contained a non-picklable class".format(filename))

## This is the central cache object 
Example #17
Source File: generate_data.py    From rtc-video-quality with Apache License 2.0 6 votes vote down vote up
def find_absolute_path(use_system_path, binary):
  global binary_absolute_paths
  if binary in binary_absolute_paths:
    return binary_absolute_paths[binary]

  if use_system_path:
    for path in os.environ["PATH"].split(os.pathsep):
      target = os.path.join(path.strip('"'), os.path.basename(binary))
      if os.path.isfile(target) and os.access(target, os.X_OK):
        binary_absolute_paths[binary] = target
        return target
  target = os.path.join(os.path.dirname(os.path.abspath(__file__)), binary)
  if os.path.isfile(target) and os.access(target, os.X_OK):
    if use_system_path:
      print "WARNING: '%s' not in PATH (using --use-system-path), falling back on locally-compiled binary." % os.path.basename(binary)
    binary_absolute_paths[binary] = target
    return target

  sys.exit("ERROR: '%s' missing, did you run the corresponding setup script?" % (os.path.basename(binary) if use_system_path else target)) 
Example #18
Source File: uuid.py    From ironpython2 with Apache License 2.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 #19
Source File: util.py    From vpn-slice with GNU General Public License v3.0 5 votes vote down vote up
def get_executable(path):
    path = which(os.path.basename(path)) or path
    if not os.access(path, os.X_OK):
        raise OSError('cannot execute {}'.format(path))
    return path 
Example #20
Source File: system.py    From stem with GNU Lesser General Public License v3.0 5 votes vote down vote up
def is_available(command: str, cached: bool = True) -> bool:
  """
  Checks the current PATH to see if a command is available or not. If more
  than one command is present (for instance "ls -a | grep foo") then this
  just checks the first.

  Note that shell (like cd and ulimit) aren't in the PATH so this lookup will
  try to assume that it's available. This only happends for recognized shell
  commands (those in SHELL_COMMANDS).

  :param command: command to search for
  :param cached: makes use of available cached results if **True**

  :returns: **True** if an executable we can use by that name exists in the
    PATH, **False** otherwise
  """

  if ' ' in command:
    command = command.split(' ')[0]

  if command in SHELL_COMMANDS:
    return True  # we can't actually look it up, so hope the shell really provides it...
  elif cached and command in CMD_AVAILABLE_CACHE:
    return CMD_AVAILABLE_CACHE[command]
  elif 'PATH' not in os.environ:
    return False  # lacking a path will cause find_executable() to internally fail

  cmd_exists = False

  for path in os.environ['PATH'].split(os.pathsep):
    cmd_path = os.path.join(path, command)

    if is_windows():
      cmd_path += '.exe'

    if os.path.exists(cmd_path) and os.access(cmd_path, os.X_OK):
      cmd_exists = True
      break

  CMD_AVAILABLE_CACHE[command] = cmd_exists
  return cmd_exists 
Example #21
Source File: cache.py    From rekall with GNU General Public License v2.0 5 votes vote down vote up
def io_manager(self):
        if not self.enabled:
            return

        cache_dir = os.path.expandvars(
            self.session.GetParameter("cache_dir", cached=False))

        cache_dir = os.path.join(config.GetHomeDir(self.session), cache_dir)

        # Force the IO manager to be recreated if the cache dir has
        # changed. This allows the session to change it's cache directory on the
        # fly (which is actually done when setting it from the command line).
        if cache_dir != self.cache_dir:
            self._io_manager = None
            self.cache_dir = cache_dir

        if self._io_manager is None and cache_dir:
            # Cache dir may be specified relative to the home directory.
            if os.access(cache_dir, os.F_OK | os.R_OK | os.W_OK | os.X_OK):
                self._io_manager = PicklingDirectoryIOManager(
                    "%s/sessions" % cache_dir, session=self.session,
                    mode="w")

                self.cache_dir = cache_dir
            else:
                self.session.logging.warn(
                    "Cache directory inaccessible. Disabling.")
                self.enabled = False

        return self._io_manager 
Example #22
Source File: solvers.py    From MatchingMarkets.py with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def executable(command):
        """Checks that the solver command is executable,
        And returns the actual path to it."""

        if os.path.isabs(command):
            if os.path.exists(command) and os.access(command, os.X_OK):
                return command
        for path in os.environ.get("PATH", []).split(os.pathsep):
            new_path = os.path.join(path, command)
            if os.path.exists(new_path) and os.access(new_path, os.X_OK):
                return os.path.join(path, command)
        return False 
Example #23
Source File: config_sql.py    From calibre-web with GNU General Public License v3.0 5 votes vote down vote up
def autodetect_kepubify_binary():
    if sys.platform == "win32":
        calibre_path = ["C:\\program files\\kepubify\\kepubify-windows-64Bit.exe",
                        "C:\\program files(x86)\\kepubify\\kepubify-windows-64Bit.exe"]
    else:
        calibre_path = ["/opt/kepubify/kepubify-linux-64bit", "/opt/kepubify/kepubify-linux-32bit"]
    for element in calibre_path:
        if os.path.isfile(element) and os.access(element, os.X_OK):
            return element
    return "" 
Example #24
Source File: util.py    From benchexec with Apache License 2.0 5 votes vote down vote up
def find_executable(program, fallback=None, exitOnError=True, use_current_dir=True):
    dirs = os.environ["PATH"].split(os.path.pathsep)
    if use_current_dir:
        dirs.append(os.path.curdir)

    found_non_executable = []  # for nicer error message
    for dir_ in dirs:
        name = os.path.join(dir_, program)
        if os.path.isfile(name):
            if os.access(name, os.X_OK):
                # file exists and is executable
                return name
            found_non_executable.append(name)

    if fallback is not None and os.path.isfile(fallback):
        if os.access(fallback, os.X_OK):
            return fallback
        found_non_executable.append(name)

    if exitOnError:
        if found_non_executable:
            sys.exit(  # noqa: R503 always raises
                "ERROR: Could not find '{0}' executable, "
                "but found file '{1}' that is not executable.".format(
                    program, found_non_executable[0]
                )
            )
        else:
            sys.exit(  # noqa: R503 always raises
                "ERROR: Could not find '{0}' executable.".format(program)
            )
    else:
        return fallback 
Example #25
Source File: ultimate.py    From benchexec with Apache License 2.0 5 votes vote down vote up
def which(self, program):
        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):
                exe_file = os.path.join(path, program)
                if is_exe(exe_file):
                    return exe_file
        return None 
Example #26
Source File: lldb.py    From debugger with MIT License 5 votes vote down vote up
def exec(self, path, args=[], **kwargs):
		if not os.access(path, os.X_OK):
			raise DebugAdapter.NotExecutableError(path)
		if subprocess.call(["DevToolsSecurity"]) != 0:
			raise DebugAdapter.PermissionDeniedError('lldb')

		# resolve path to debugserver
		path_debugserver = shutil.which('debugserver')
		if not path_debugserver:
			path_debugserver = '/Library/Developer/CommandLineTools/Library/' + \
			'PrivateFrameworks/LLDB.framework/Versions/A/Resources/debugserver'
		if not os.path.exists(path_debugserver):
			raise DebugAdapter.NotInstalledError('lldb')

		# get available port
		port = gdblike.get_available_port()
		if port == None:
			raise Exception('no available ports')

		# invoke debugserver
		try:
			if kwargs.get('terminal', False):
				dbg_args = [path_debugserver]
				dbg_args.extend(['--stdio-path', '/dev/stdin'])
				dbg_args.extend(['--stdout-path', '/dev/stdout'])
				dbg_args.extend(['--stderr-path', '/dev/stderr'])
				dbg_args.extend(['localhost:%d'%port, shlex.quote(path), '--'])
				dbg_args.extend([shlex.quote(arg) for arg in args])
				DebugAdapter.new_terminal(' '.join(dbg_args))
			else:
				dbg_args = [path_debugserver, 'localhost:%d'%port, path, '--']
				dbg_args.extend(args)
				subprocess.Popen(dbg_args, stdin=None, stdout=None, stderr=None, preexec_fn=gdblike.preexec)
		except Exception:
			raise Exception('invoking debugserver (used path: %s)' % path_debugserver)

		self.target_path_ = path
		self.connect('localhost', port) 
Example #27
Source File: test_uuid.py    From ironpython2 with Apache License 2.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):
            if sys.platform == 'cli':
                return io.StringIO(data)
            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 #28
Source File: helpers.py    From specter-desktop with MIT License 5 votes vote down vote up
def which(program):
    ''' mimics the "which" command in bash but even for stuff not on the path.
        Also has implicit pyinstaller support 
        Place your executables like --add-binary '.env/bin/hwi:.'
        ... and they will be found.
        returns a full path of the executable and if a full path is passed,
        it will simply return it if found and executable
        will raise an Exception if not found
    '''
    
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

    if getattr(sys, 'frozen', False):
        # Best understood with the snippet below this section:
        # https://pyinstaller.readthedocs.io/en/v3.3.1/runtime-information.html#using-sys-executable-and-sys-argv-0
        exec_location = os.path.join(sys._MEIPASS, program)
        if is_exe(exec_location):
            logger.info("Found %s executable in %s" % (program, exec_location))
            return exec_location

    fpath, program_name = os.path.split(program)
    if fpath:
        if is_exe(program):
            logger.info("Found %s executable in %s" % (program, 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):
                logger.info("Found %s executable in %s" % (program, path))
                return exe_file
    raise Exception("Couldn't find executable %s" % program)

# should work in all python versions 
Example #29
Source File: test_install.py    From nanopype with MIT License 5 votes vote down vote up
def __is_exe__(fpath):
    return os.path.isfile(fpath) and os.access(fpath, os.X_OK)


# Test cases 
Example #30
Source File: custom.py    From azure-cli-extensions with MIT License 5 votes vote down vote up
def which(binary):
    path_var = os.getenv('PATH')
    if platform.system() == 'Windows':
        binary = binary + '.exe'
        parts = path_var.split(';')
    else:
        parts = path_var.split(':')

    for part in parts:
        bin_path = os.path.join(part, binary)
        if os.path.exists(bin_path) and os.path.isfile(bin_path) and os.access(bin_path, os.X_OK):
            return bin_path

    return None