Python os.access() Examples

The following are code examples for showing how to use os.access(). 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: Ansible-Example-AB2018   Author: umit-ozturk   File: filesystem.py    MIT License 6 votes vote down vote up
def check_path_owner(path):
    # If we don't have a way to check the effective uid of this process, then
    # we'll just assume that we own the directory.
    if not hasattr(os, "geteuid"):
        return True

    previous = None
    while path != previous:
        if os.path.lexists(path):
            # Check if path is writable by current user.
            if os.geteuid() == 0:
                # Special handling for root user in order to handle properly
                # cases where users use sudo without -H flag.
                try:
                    path_uid = get_path_uid(path)
                except OSError:
                    return False
                return path_uid == 0
            else:
                return os.access(path, os.W_OK)
        else:
            previous, path = path, os.path.dirname(path) 
Example 5
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: user.py    MIT License 6 votes vote down vote up
def user_password(self):
        passwd = ''
        if HAVE_SPWD:
            try:
                passwd = spwd.getspnam(self.name)[1]
            except KeyError:
                return passwd
        if not self.user_exists():
            return passwd
        elif self.SHADOWFILE:
            # Read shadow file for user's encrypted password string
            if os.path.exists(self.SHADOWFILE) and os.access(self.SHADOWFILE, os.R_OK):
                for line in open(self.SHADOWFILE).readlines():
                    if line.startswith('%s:' % self.name):
                        passwd = line.split(':')[1]
        return passwd 
Example 6
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 7
Project: PickTrue   Author: winkidney   File: downloader.py    MIT License 6 votes vote down vote up
def start_download(self):
        self.url.assert_no_error()
        self.username.assert_no_error()
        self.password.assert_no_error()
        self.proxy.assert_no_error()
        self.save_path.assert_no_error()

        url = self.url.get_input()
        proxy = self.proxy.get_input() or None
        username = self.username.get_input()
        password = self.password.get_input()
        path_prefix = self.save_path.get_path()

        if not os.access(path_prefix, os.W_OK):
            return info("对下载文件夹没有写权限,请重新选择")
        if self.downloader is not None:
            if not self.downloader.done:
                return info("请停止后再重新点击下载...")
        self.downloader = pixiv_run(
            url=url,
            username=username,
            password=password,
            proxy=proxy,
            path_prefix=path_prefix,
        ) 
Example 8
Project: PickTrue   Author: winkidney   File: downloader.py    MIT License 6 votes vote down vote up
def start_download(self):
        self.url.assert_no_error()
        self.save_path.assert_no_error()
        self.proxy.assert_no_error()

        url = self.url.get_input()
        path_prefix = self.save_path.get_path()
        proxy = self.proxy.get_input()

        if not os.access(path_prefix, os.W_OK):
            return info("对下载文件夹没有写权限,请重新选择")
        if self.downloader is not None:
            if not self.downloader.done:
                return info("请停止后再重新点击下载...")
        self.downloader = self.run(
            url=url,
            path_prefix=path_prefix,
            proxy=proxy,
        ) 
Example 9
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: driver.py    Apache License 2.0 6 votes vote down vote up
def _get_cpu_numa_config_from_instance(self, instance_numa_topology,
                                           wants_hugepages):
        if instance_numa_topology:
            guest_cpu_numa = vconfig.LibvirtConfigGuestCPUNUMA()
            for instance_cell in instance_numa_topology.cells:
                guest_cell = vconfig.LibvirtConfigGuestCPUNUMACell()
                guest_cell.id = instance_cell.id
                guest_cell.cpus = instance_cell.cpuset
                guest_cell.memory = instance_cell.memory * units.Ki

                # The vhost-user network backend requires file backed
                # guest memory (ie huge pages) to be marked as shared
                # access, not private, so an external process can read
                # and write the pages.
                #
                # You can't change the shared vs private flag for an
                # already running guest, and since we can't predict what
                # types of NIC may be hotplugged, we have no choice but
                # to unconditionally turn on the shared flag. This has
                # no real negative functional effect on the guest, so
                # is a reasonable approach to take
                if wants_hugepages:
                    guest_cell.memAccess = "shared"
                guest_cpu_numa.cells.append(guest_cell)
            return guest_cpu_numa 
Example 10
Project: sic   Author: Yanixos   File: filesystem.py    GNU General Public License v3.0 6 votes vote down vote up
def check_path_owner(path):
    # If we don't have a way to check the effective uid of this process, then
    # we'll just assume that we own the directory.
    if not hasattr(os, "geteuid"):
        return True

    previous = None
    while path != previous:
        if os.path.lexists(path):
            # Check if path is writable by current user.
            if os.geteuid() == 0:
                # Special handling for root user in order to handle properly
                # cases where users use sudo without -H flag.
                try:
                    path_uid = get_path_uid(path)
                except OSError:
                    return False
                return path_uid == 0
            else:
                return os.access(path, os.W_OK)
        else:
            previous, path = path, os.path.dirname(path) 
Example 11
Project: AshsSDK   Author: thehappydinoa   File: filesystem.py    MIT License 6 votes vote down vote up
def check_path_owner(path):
    # If we don't have a way to check the effective uid of this process, then
    # we'll just assume that we own the directory.
    if not hasattr(os, "geteuid"):
        return True

    previous = None
    while path != previous:
        if os.path.lexists(path):
            # Check if path is writable by current user.
            if os.geteuid() == 0:
                # Special handling for root user in order to handle properly
                # cases where users use sudo without -H flag.
                try:
                    path_uid = get_path_uid(path)
                except OSError:
                    return False
                return path_uid == 0
            else:
                return os.access(path, os.W_OK)
        else:
            previous, path = path, os.path.dirname(path) 
Example 12
Project: factotum   Author: Denubis   File: update.py    GNU General Public License v3.0 5 votes vote down vote up
def updateFactorio():
	

	file_name = "/tmp/latestFactorio.tar.gz"
	print("Downloading %s" % file_name)

	r = requests.get(DOWNLOADURL, stream=True)
	total_length = int(r.headers.get('content-length'))

	if not os.path.isfile(file_name) or total_length != os.path.getsize(file_name):
		with open(file_name, 'wb') as f:
			for chunk in progress.bar(r.iter_content(chunk_size=1024), expected_size=(total_length/1024) + 1): 
				if chunk:
					f.write(chunk)
					f.flush()
			#os.chmod(file_name, stat.S_IWUSR | stat.S_IRUSR)
	else:
		print("File already exists and file sizes match. Skipping download.")	

	if os.access(FACTORIOPATH, os.W_OK):
		if os.path.isfile(file_name):
			tar = tarfile.open(file_name, "r:gz")
			tar.extractall(path="/tmp")
			tar.close()

			copytree("/tmp/factorio", FACTORIOPATH)
			print("Success.")
		else:
			print("Help! Can't find %s, but I should have!" % (file_name))
			sys.exit(1)			
	else:
		print("Can't write to %s" % (FACTORIOPATH))
		sys.exit(1) 
Example 13
Project: factotum   Author: Denubis   File: update.py    GNU General Public License v3.0 5 votes vote down vote up
def safeInstall():
	FACTORIOPATH = getFactorioPath()

	try:
		if not os.path.isdir("%s" % (FACTORIOPATH) ):		

			if os.access("%s/.." % (FACTORIOPATH), os.W_OK):
				os.mkdir(FACTORIOPATH, 0o777)
			else:
				subprocess.call(['sudo', 'mkdir', '-p', FACTORIOPATH])
				subprocess.call(['sudo', 'chown', getpass.getuser(), FACTORIOPATH])
							

			os.mkdir(os.path.join(FACTORIOPATH, "saves"))
			os.mkdir(os.path.join(FACTORIOPATH, "config"))
			with open("%s/.bashrc" % (os.path.expanduser("~")), "r+") as bashrc:
				lines = bashrc.read()
				
				if lines.find("eval \"$(_FACTOTUM_COMPLETE=source factotum)\"\n") == -1:
					bashrc.write("eval \"$(_FACTOTUM_COMPLETE=source factotum)\"\n")
					print("You'll want to restart your shell for command autocompletion. Tab is your friend.")
		updateFactorio()
	except IOError as e:
		print("Cannot make %s. Please check permissions. Error %s" % (FACTORIOPATH, e))
		sys.exit(1) 
Example 14
Project: factotum   Author: Denubis   File: factoriopath.py    GNU General Public License v3.0 5 votes vote down vote up
def getFactorioPath():
    try:
        with open("%s/.factorioPath" % (os.path.expanduser("~")), "r") as data_file:
            path = data_file.readline().strip()
    except:
        print("%s/.factorioPath not found. Using default." % (os.path.expanduser("~")))
        if os.path.isdir("/opt/factorio"):
            path = "/opt/factorio"
        elif os.access("/opt", os.W_OK):
            path = "/opt/factorio"
        else:
            path = "%s/factorio" % (os.path.expanduser("~"))
    return path 
Example 15
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 16
Project: leapp-repository   Author: oamg   File: library.py    Apache License 2.0 5 votes vote down vote up
def _is_file_readable(path):
    ''' Verify if file exists and is readable '''
    return os.path.isfile(path) and os.access(path, os.R_OK) 
Example 17
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 18
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_access(self):
        f = os.open(test_support.TESTFN, os.O_CREAT|os.O_RDWR)
        os.close(f)
        self.assertTrue(os.access(test_support.TESTFN, os.W_OK)) 
Example 19
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_statvfs_attributes(self):
        try:
            result = os.statvfs(self.fname)
        except OSError, e:
            # On AtheOS, glibc always returns ENOSYS
            if e.errno == errno.ENOSYS:
                self.skipTest('glibc always returns ENOSYS on AtheOS')

        # Make sure direct access works 
Example 20
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 21
Project: pyblish-win   Author: pyblish   File: test_unicode_file.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _do_single(self, filename):
        self.assertTrue(os.path.exists(filename))
        self.assertTrue(os.path.isfile(filename))
        self.assertTrue(os.access(filename, os.R_OK))
        self.assertTrue(os.path.exists(os.path.abspath(filename)))
        self.assertTrue(os.path.isfile(os.path.abspath(filename)))
        self.assertTrue(os.access(os.path.abspath(filename), os.R_OK))
        os.chmod(filename, 0777)
        os.utime(filename, None)
        os.utime(filename, (time.time(), time.time()))
        # Copy/rename etc tests using the same filename
        self._do_copyish(filename, filename)
        # Filename should appear in glob output
        self.assertTrue(
            os.path.abspath(filename)==os.path.abspath(glob.glob(filename)[0]))
        # basename should appear in listdir.
        path, base = os.path.split(os.path.abspath(filename))
        if isinstance(base, str):
            base = base.decode(TESTFN_ENCODING)
        file_list = os.listdir(path)
        # listdir() with a unicode arg may or may not return Unicode
        # objects, depending on the platform.
        if file_list and isinstance(file_list[0], str):
            file_list = [f.decode(TESTFN_ENCODING) for f in file_list]

        # Normalize the unicode strings, as round-tripping the name via the OS
        # may return a different (but equivalent) value.
        base = unicodedata.normalize("NFD", base)
        file_list = [unicodedata.normalize("NFD", f) for f in file_list]

        self.assertIn(base, file_list)

    # Do as many "equivalancy' tests as we can - ie, check that although we
    # have different types for the filename, they refer to the same file. 
Example 22
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def is_writable(self, path):
        result = False
        while not result:
            if os.path.exists(path):
                result = os.access(path, os.W_OK)
                break
            parent = os.path.dirname(path)
            if parent == path:
                break
            path = parent
        return result 
Example 23
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: util.py    MIT License 5 votes vote down vote up
def get_cache_base(suffix=None):
    """
    Return the default base location for distlib caches. If the directory does
    not exist, it is created. Use the suffix provided for the base directory,
    and default to '.distlib' if it isn't provided.

    On Windows, if LOCALAPPDATA is defined in the environment, then it is
    assumed to be a directory, and will be the parent directory of the result.
    On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
    directory - using os.expanduser('~') - will be the parent directory of
    the result.

    The result is just the directory '.distlib' in the parent directory as
    determined above, or with the name specified with ``suffix``.
    """
    if suffix is None:
        suffix = '.distlib'
    if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
        result = os.path.expandvars('$localappdata')
    else:
        # Assume posix, or old Windows
        result = os.path.expanduser('~')
    # we use 'isdir' instead of 'exists', because we want to
    # fail if there's a file with that name
    if os.path.isdir(result):
        usable = os.access(result, os.W_OK)
        if not usable:
            logger.warning('Directory exists but is not writable: %s', result)
    else:
        try:
            os.makedirs(result)
            usable = True
        except OSError:
            logger.warning('Unable to create %s', result, exc_info=True)
            usable = False
    if not usable:
        result = tempfile.mkdtemp()
        logger.warning('Default location unusable, using %s', result)
    return os.path.join(result, suffix) 
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: bigip_ucs_fetch.py    MIT License 5 votes vote down vote up
def fulldest(self):
        result = None
        if os.path.isdir(self.dest):
            result = os.path.join(self.dest, self.src)
        else:
            if os.path.exists(os.path.dirname(self.dest)):
                result = self.dest
            else:
                try:
                    # os.path.exists() can return false in some
                    # circumstances where the directory does not have
                    # the execute bit for the current user set, in
                    # which case the stat() call will raise an OSError
                    os.stat(os.path.dirname(result))
                except OSError as e:
                    if "permission denied" in str(e).lower():
                        raise F5ModuleError(
                            "Destination directory {0} is not accessible".format(os.path.dirname(result))
                        )
                    raise F5ModuleError(
                        "Destination directory {0} does not exist".format(os.path.dirname(result))
                    )

        if not os.access(os.path.dirname(result), os.W_OK):
            raise F5ModuleError(
                "Destination {0} not writable".format(os.path.dirname(result))
            )
        return result 
Example 26
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 27
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: dnf.py    MIT License 5 votes vote down vote up
def _configure_base(module, base, conf_file, disable_gpg_check, installroot='/'):
    """Configure the dnf Base object."""
    conf = base.conf

    # Turn off debug messages in the output
    conf.debuglevel = 0

    # Set whether to check gpg signatures
    conf.gpgcheck = not disable_gpg_check

    # Don't prompt for user confirmations
    conf.assumeyes = True

    # Set installroot
    conf.installroot = installroot

    # Change the configuration file path if provided
    if conf_file:
        # Fail if we can't read the configuration file.
        if not os.access(conf_file, os.R_OK):
            module.fail_json(
                msg="cannot read configuration file", conf_file=conf_file)
        else:
            conf.config_file_path = conf_file

    # Read the configuration file
    conf.read() 
Example 28
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 29
Project: 2015-SpaceInvaders-Bot-Python   Author: EntelectChallenge   File: ez_setup.py    MIT License 5 votes vote down vote up
def _clean_check(cmd, target):
    """
    Run the command to download target.

    If the command fails, clean up before re-raising the error.
    """
    try:
        subprocess.check_call(cmd)
    except subprocess.CalledProcessError:
        if os.access(target, os.F_OK):
            os.unlink(target)
        raise 
Example 30
Project: scriptfs   Author: iffy   File: scriptfs.py    Apache License 2.0 5 votes vote down vote up
def access(self, mode):
        if not os.access(self.root, mode):
            raise FuseOSError(errno.EACCES) 
Example 31
Project: scriptfs   Author: iffy   File: scriptfs.py    Apache License 2.0 5 votes vote down vote up
def access(self, mode):
        pass 
Example 32
Project: flasky   Author: RoseOu   File: util.py    MIT License 5 votes vote down vote up
def is_writable(self, path):
        result = False
        while not result:
            if os.path.exists(path):
                result = os.access(path, os.W_OK)
                break
            parent = os.path.dirname(path)
            if parent == path:
                break
            path = parent
        return result 
Example 33
Project: flasky   Author: RoseOu   File: util.py    MIT License 5 votes vote down vote up
def get_cache_base(suffix=None):
    """
    Return the default base location for distlib caches. If the directory does
    not exist, it is created. Use the suffix provided for the base directory,
    and default to '.distlib' if it isn't provided.

    On Windows, if LOCALAPPDATA is defined in the environment, then it is
    assumed to be a directory, and will be the parent directory of the result.
    On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
    directory - using os.expanduser('~') - will be the parent directory of
    the result.

    The result is just the directory '.distlib' in the parent directory as
    determined above, or with the name specified with ``suffix``.
    """
    if suffix is None:
        suffix = '.distlib'
    if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
        result = os.path.expandvars('$localappdata')
    else:
        # Assume posix, or old Windows
        result = os.path.expanduser('~')
    result = os.path.join(result, suffix)
    # we use 'isdir' instead of 'exists', because we want to
    # fail if there's a file with that name
    if os.path.isdir(result):
        usable = os.access(result, os.W_OK)
        if not usable:
            logger.warning('Directory exists but is not writable: %s', result)
    else:
        try:
            os.makedirs(result)
            usable = True
        except OSError:
            logger.warning('Unable to create %s', result, exc_info=True)
            usable = False
    if not usable:
        result = tempfile.mkdtemp()
        logger.warning('Default location unusable, using %s', result)
    return result 
Example 34
Project: flasky   Author: RoseOu   File: pkg_resources.py    MIT License 5 votes vote down vote up
def extraction_error(self):
        """Give an error message for problems extracting file(s)"""

        old_exc = sys.exc_info()[1]
        cache_path = self.extraction_path or get_default_cache()

        err = ExtractionError("""Can't extract file(s) to egg cache

The following error occurred while trying to extract file(s) to the Python egg
cache:

  %s

The Python egg cache directory is currently set to:

  %s

Perhaps your account does not have write access to this directory?  You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory.
""" % (old_exc, cache_path)
        )
        err.manager = self
        err.cache_path = cache_path
        err.original_error = old_exc
        raise err 
Example 35
Project: flasky   Author: RoseOu   File: pkg_resources.py    MIT License 5 votes vote down vote up
def find_on_path(importer, path_item, only=False):
    """Yield distributions accessible on a sys.path directory"""
    path_item = _normalize_cached(path_item)

    if os.path.isdir(path_item) and os.access(path_item, os.R_OK):
        if path_item.lower().endswith('.egg'):
            # unpacked egg
            yield Distribution.from_filename(
                path_item, metadata=PathMetadata(
                    path_item, os.path.join(path_item,'EGG-INFO')
                )
            )
        else:
            # scan for .egg and .egg-info in directory
            for entry in os.listdir(path_item):
                lower = entry.lower()
                if lower.endswith('.egg-info') or lower.endswith('.dist-info'):
                    fullpath = os.path.join(path_item, entry)
                    if os.path.isdir(fullpath):
                        # egg-info directory, allow getting metadata
                        metadata = PathMetadata(path_item, fullpath)
                    else:
                        metadata = FileMetadata(fullpath)
                    yield Distribution.from_location(
                        path_item,entry,metadata,precedence=DEVELOP_DIST
                    )
                elif not only and lower.endswith('.egg'):
                    for dist in find_distributions(os.path.join(path_item, entry)):
                        yield dist
                elif not only and lower.endswith('.egg-link'):
                    entry_file = open(os.path.join(path_item, entry))
                    try:
                        entry_lines = entry_file.readlines()
                    finally:
                        entry_file.close()
                    for line in entry_lines:
                        if not line.strip(): continue
                        for item in find_distributions(os.path.join(path_item,line.rstrip())):
                            yield item
                        break 
Example 36
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 37
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 38
Project: flasky   Author: RoseOu   File: script.py    MIT License 5 votes vote down vote up
def __init__(self, dir, file_template=_default_file_template,
                    truncate_slug_length=40):
        self.dir = dir
        self.versions = os.path.join(self.dir, 'versions')
        self.file_template = file_template
        self.truncate_slug_length = truncate_slug_length or 40

        if not os.access(dir, os.F_OK):
            raise util.CommandError("Path doesn't exist: %r.  Please use "
                        "the 'init' command to create a new "
                        "scripts folder." % dir) 
Example 39
Project: flasky   Author: RoseOu   File: command.py    MIT License 5 votes vote down vote up
def init(config, directory, template='generic'):
    """Initialize a new scripts directory."""

    if os.access(directory, os.F_OK):
        raise util.CommandError("Directory %s already exists" % directory)

    template_dir = os.path.join(config.get_template_directory(),
                                    template)
    if not os.access(template_dir, os.F_OK):
        raise util.CommandError("No such template %r" % template)

    util.status("Creating directory %s" % os.path.abspath(directory),
                os.makedirs, directory)

    versions = os.path.join(directory, 'versions')
    util.status("Creating directory %s" % os.path.abspath(versions),
                os.makedirs, versions)

    script = ScriptDirectory(directory)

    for file_ in os.listdir(template_dir):
        file_path = os.path.join(template_dir, file_)
        if file_ == 'alembic.ini.mako':
            config_file = os.path.abspath(config.config_file_name)
            if os.access(config_file, os.F_OK):
                util.msg("File %s already exists, skipping" % config_file)
            else:
                script._generate_template(
                    file_path,
                    config_file,
                    script_location=directory
                )
        elif os.path.isfile(file_path):
            output_file = os.path.join(directory, file_)
            script._copy_file(
                file_path,
                output_file
            )

    util.msg("Please edit configuration/connection/logging "\
            "settings in %r before proceeding." % config_file) 
Example 40
Project: flasky   Author: RoseOu   File: pkg_resources.py    MIT License 5 votes vote down vote up
def extraction_error(self):
        """Give an error message for problems extracting file(s)"""

        old_exc = sys.exc_info()[1]
        cache_path = self.extraction_path or get_default_cache()

        err = ExtractionError("""Can't extract file(s) to egg cache

The following error occurred while trying to extract file(s) to the Python egg
cache:

  %s

The Python egg cache directory is currently set to:

  %s

Perhaps your account does not have write access to this directory?  You can
change the cache directory by setting the PYTHON_EGG_CACHE environment
variable to point to an accessible directory.
""" % (old_exc, cache_path)
        )
        err.manager = self
        err.cache_path = cache_path
        err.original_error = old_exc
        raise err 
Example 41
Project: flasky   Author: RoseOu   File: pkg_resources.py    MIT License 5 votes vote down vote up
def find_on_path(importer, path_item, only=False):
    """Yield distributions accessible on a sys.path directory"""
    path_item = _normalize_cached(path_item)

    if os.path.isdir(path_item) and os.access(path_item, os.R_OK):
        if path_item.lower().endswith('.egg'):
            # unpacked egg
            yield Distribution.from_filename(
                path_item, metadata=PathMetadata(
                    path_item, os.path.join(path_item,'EGG-INFO')
                )
            )
        else:
            # scan for .egg and .egg-info in directory
            for entry in os.listdir(path_item):
                lower = entry.lower()
                if lower.endswith('.egg-info') or lower.endswith('.dist-info'):
                    fullpath = os.path.join(path_item, entry)
                    if os.path.isdir(fullpath):
                        # egg-info directory, allow getting metadata
                        metadata = PathMetadata(path_item, fullpath)
                    else:
                        metadata = FileMetadata(fullpath)
                    yield Distribution.from_location(
                        path_item,entry,metadata,precedence=DEVELOP_DIST
                    )
                elif not only and lower.endswith('.egg'):
                    for dist in find_distributions(os.path.join(path_item, entry)):
                        yield dist
                elif not only and lower.endswith('.egg-link'):
                    entry_file = open(os.path.join(path_item, entry))
                    try:
                        entry_lines = entry_file.readlines()
                    finally:
                        entry_file.close()
                    for line in entry_lines:
                        if not line.strip(): continue
                        for item in find_distributions(os.path.join(path_item,line.rstrip())):
                            yield item
                        break 
Example 42
Project: numpynet   Author: uptake   File: loggit.py    BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def changeFileName(self, new_name, header=None, onConsole=True, onFile=True):
        """
        Change the name of the log
        new_name
        header (str) - A string describing the type of header information you
                       want with the logs passed to startLog: 'simple',
                       'message_only', 'no_time', <custom header>
                       (see startLog for more details on formatting)
        onConsole (bool) - True if you want logs written to the console
        onFile (bool)    - True if you want the log written to the file
        """
        # Get rid of tildas
        new_name = os.path.expanduser(new_name)
        # Check if name is okay
        # Copy old log to new name
        new_path, new_filename = os.path.split(new_name)
        if new_path == "":
            new_path = self.filePath
        new_full_filename = os.path.join(new_path, new_filename)
        if os.access(new_path, os.W_OK):
            self.out.handlers = []  # clear old handlers
            if self.onFile:
                copyfile(self.fileFullName, new_full_filename)
                os.remove(self.fileFullName)
            self.startLog(
                filePath=new_path,
                fileName=new_filename,
                header=header,
                onConsole=onConsole,
                onFile=onFile,
            )
        else:
            log.out.warning("No permissions to write new log name")


# Make a global log object to share 
Example 43
Project: o2g   Author: hiposfer   File: cli.py    MIT License 5 votes vote down vote up
def __call__(self, parser, namespace, prospective_dir, option_string=None):
        if not os.path.isdir(prospective_dir):
            parser.print_usage()
            print('Try "{} --help" for help.\n'.format(parser.prog))
            parser.exit("Error: Invalid path: {0}".format(prospective_dir))
        if os.access(prospective_dir, os.R_OK):
            setattr(namespace, self.dest, prospective_dir)
        else:
            parser.print_usage()
            print('Try "{} --help" for help.\n'.format(parser.prog))
            parser.exit("Error: Unreadable dir: {0}".format(prospective_dir)) 
Example 44
Project: o2g   Author: hiposfer   File: cli.py    MIT License 5 votes vote down vote up
def __call__(self, parser, namespace, prospective_file, option_string=None):
        if not os.path.isfile(prospective_file):
            parser.print_usage()
            print('Try "{} --help" for help.\n'.format(parser.prog))
            parser.exit("Error: Invalid file: {0}".format(prospective_file))
        if os.access(prospective_file, os.R_OK):
            setattr(namespace, self.dest, prospective_file)
        else:
            parser.print_usage()
            print('Try "{} --help" for help.\n'.format(parser.prog))
            parser.exit("Error: Unreadable file: {0}".format(prospective_file)) 
Example 45
Project: PickTrue   Author: winkidney   File: downloader.py    MIT License 5 votes vote down vote up
def start_download(self):
        self.url.assert_no_error()
        self.save_path.assert_no_error()
        url = self.url.get_input()
        path_prefix = self.save_path.get_path()
        if not os.access(path_prefix, os.W_OK):
            return info("对下载文件夹没有写权限,请重新选择")
        if self.downloader is not None:
            if not self.downloader.done:
                return info("请停止后再重新点击下载...")
        self.downloader = self.run(
            url=url,
            path_prefix=path_prefix,
        ) 
Example 46
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 47
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 48
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 49
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 50
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: imagebackend.py    Apache License 2.0 5 votes vote down vote up
def cache(self, fetch_func, filename, size=None, *args, **kwargs):
        """Creates image from template.

        Ensures that template and image not already exists.
        Ensures that base directory exists.
        Synchronizes on template fetching.

        :fetch_func: Function that creates the base image
                     Should accept `target` argument.
        :filename: Name of the file in the image directory
        :size: Size of created image in bytes (optional)
        """
        @utils.synchronized(filename, external=True, lock_path=self.lock_path)
        def fetch_func_sync(target, *args, **kwargs):
            # The image may have been fetched while a subsequent
            # call was waiting to obtain the lock.
            if not os.path.exists(target):
                fetch_func(target=target, *args, **kwargs)

        base_dir = os.path.join(CONF.instances_path,
                                CONF.image_cache_subdirectory_name)
        if not os.path.exists(base_dir):
            fileutils.ensure_tree(base_dir)
        base = os.path.join(base_dir, filename)

        if not self.check_image_exists() or not os.path.exists(base):
            self.create_image(fetch_func_sync, base, size,
                              *args, **kwargs)

        if size:
            if size > self.get_disk_size(base):
                self.resize_image(size)

            if (self.preallocate and self._can_fallocate() and
                    os.access(self.path, os.W_OK)):
                utils.execute('fallocate', '-n', '-l', size, self.path) 
Example 51
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: imagebackend.py    Apache License 2.0 5 votes vote down vote up
def direct_snapshot(self, context, snapshot_name, image_format,
                        image_id, base_image_id):
        """Creates an RBD snapshot directly.
        """
        fsid = self.driver.get_fsid()
        # NOTE(nic): Nova has zero comprehension of how Glance's image store
        # is configured, but we can infer what storage pool Glance is using
        # by looking at the parent image.  If using authx, write access should
        # be enabled on that pool for the Nova user
        parent_pool = self._get_parent_pool(context, base_image_id, fsid)

        # Snapshot the disk and clone it into Glance's storage pool.  librbd
        # requires that snapshots be set to "protected" in order to clone them
        self.driver.create_snap(self.rbd_name, snapshot_name, protect=True)
        location = {'url': 'rbd://%(fsid)s/%(pool)s/%(image)s/%(snap)s' %
                           dict(fsid=fsid,
                                pool=self.pool,
                                image=self.rbd_name,
                                snap=snapshot_name)}
        try:
            self.driver.clone(location, image_id, dest_pool=parent_pool)
            # Flatten the image, which detaches it from the source snapshot
            self.driver.flatten(image_id, pool=parent_pool)
        finally:
            # all done with the source snapshot, clean it up
            self.cleanup_direct_snapshot(location)

        # Glance makes a protected snapshot called 'snap' on uploaded
        # images and hands it out, so we'll do that too.  The name of
        # the snapshot doesn't really matter, this just uses what the
        # glance-store rbd backend sets (which is not configurable).
        self.driver.create_snap(image_id, 'snap', pool=parent_pool,
                                protect=True)
        return ('rbd://%(fsid)s/%(pool)s/%(image)s/snap' %
                dict(fsid=fsid, pool=parent_pool, image=image_id)) 
Example 52
Project: Trusted-Platform-Module-nova   Author: BU-NU-CLOUD-SP16   File: test_scality.py    Apache License 2.0 5 votes vote down vote up
def test_connect_volume(self, mock_urlopen):
        TEST_VOLDIR = 'volumes'
        TEST_VOLNAME = 'volume_name'
        TEST_CONN_INFO = {
            'data': {
                'sofs_path': os.path.join(TEST_VOLDIR, TEST_VOLNAME)
            }
        }
        TEST_VOLPATH = os.path.join(self.scality_sofs_mount_point,
                                    TEST_VOLDIR,
                                    TEST_VOLNAME)

        def _access_wrapper(path, flags):
            if path == '/sbin/mount.sofs':
                return True
            else:
                return os.access(path, flags)

        self.stub_out('os.access', _access_wrapper)

        with mock.patch.object(self.drv, '_mount_sofs'):
            self.drv.connect_volume(TEST_CONN_INFO, self.disk_info)

        device_path = os.path.join(self.scality_sofs_mount_point,
                                   TEST_CONN_INFO['data']['sofs_path'])
        self.assertEqual(TEST_CONN_INFO['data']['device_path'], device_path)

        conf = self.drv.get_config(TEST_CONN_INFO, self.disk_info)
        tree = conf.format_dom()
        self._assertFileTypeEquals(tree, TEST_VOLPATH) 
Example 53
Project: sic   Author: Yanixos   File: tempfile.py    GNU General Public License v3.0 5 votes vote down vote up
def _mkstemp_inner(dir, pre, suf, flags, output_type):
    """Code common to mkstemp, TemporaryFile, and NamedTemporaryFile."""

    names = _get_candidate_names()
    if output_type is bytes:
        names = map(_os.fsencode, names)

    for seq in range(TMP_MAX):
        name = next(names)
        file = _os.path.join(dir, pre + name + suf)
        try:
            fd = _os.open(file, flags, 0o600)
        except FileExistsError:
            continue    # try again
        except PermissionError:
            # This exception is thrown when a directory with the chosen name
            # already exists on windows.
            if (_os.name == 'nt' and _os.path.isdir(dir) and
                _os.access(dir, _os.W_OK)):
                continue
            else:
                raise
        return (fd, _os.path.abspath(file))

    raise FileExistsError(_errno.EEXIST,
                          "No usable temporary file name found")


# User visible interfaces. 
Example 54
Project: sic   Author: Yanixos   File: tempfile.py    GNU General Public License v3.0 5 votes vote down vote up
def mkdtemp(suffix=None, prefix=None, dir=None):
    """User-callable function to create and return a unique temporary
    directory.  The return value is the pathname of the directory.

    Arguments are as for mkstemp, except that the 'text' argument is
    not accepted.

    The directory is readable, writable, and searchable only by the
    creating user.

    Caller is responsible for deleting the directory when done with it.
    """

    prefix, suffix, dir, output_type = _sanitize_params(prefix, suffix, dir)

    names = _get_candidate_names()
    if output_type is bytes:
        names = map(_os.fsencode, names)

    for seq in range(TMP_MAX):
        name = next(names)
        file = _os.path.join(dir, prefix + name + suffix)
        try:
            _os.mkdir(file, 0o700)
        except FileExistsError:
            continue    # try again
        except PermissionError:
            # This exception is thrown when a directory with the chosen name
            # already exists on windows.
            if (_os.name == 'nt' and _os.path.isdir(dir) and
                _os.access(dir, _os.W_OK)):
                continue
            else:
                raise
        return file

    raise FileExistsError(_errno.EEXIST,
                          "No usable temporary directory name found") 
Example 55
Project: sic   Author: Yanixos   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def extraction_error(self):
        """Give an error message for problems extracting file(s)"""

        old_exc = sys.exc_info()[1]
        cache_path = self.extraction_path or get_default_cache()

        tmpl = textwrap.dedent("""
            Can't extract file(s) to egg cache

            The following error occurred while trying to extract file(s) to the Python egg
            cache:

              {old_exc}

            The Python egg cache directory is currently set to:

              {cache_path}

            Perhaps your account does not have write access to this directory?  You can
            change the cache directory by setting the PYTHON_EGG_CACHE environment
            variable to point to an accessible directory.
            """).lstrip()
        err = ExtractionError(tmpl.format(**locals()))
        err.manager = self
        err.cache_path = cache_path
        err.original_error = old_exc
        raise err 
Example 56
Project: sic   Author: Yanixos   File: __init__.py    GNU General Public License v3.0 5 votes vote down vote up
def extraction_error(self):
        """Give an error message for problems extracting file(s)"""

        old_exc = sys.exc_info()[1]
        cache_path = self.extraction_path or get_default_cache()

        tmpl = textwrap.dedent("""
            Can't extract file(s) to egg cache

            The following error occurred while trying to extract file(s) to the Python egg
            cache:

              {old_exc}

            The Python egg cache directory is currently set to:

              {cache_path}

            Perhaps your account does not have write access to this directory?  You can
            change the cache directory by setting the PYTHON_EGG_CACHE environment
            variable to point to an accessible directory.
            """).lstrip()
        err = ExtractionError(tmpl.format(**locals()))
        err.manager = self
        err.cache_path = cache_path
        err.original_error = old_exc
        raise err 
Example 57
Project: sic   Author: Yanixos   File: util.py    GNU General Public License v3.0 5 votes vote down vote up
def is_writable(self, path):
        result = False
        while not result:
            if os.path.exists(path):
                result = os.access(path, os.W_OK)
                break
            parent = os.path.dirname(path)
            if parent == path:
                break
            path = parent
        return result 
Example 58
Project: sic   Author: Yanixos   File: util.py    GNU General Public License v3.0 5 votes vote down vote up
def get_cache_base(suffix=None):
    """
    Return the default base location for distlib caches. If the directory does
    not exist, it is created. Use the suffix provided for the base directory,
    and default to '.distlib' if it isn't provided.

    On Windows, if LOCALAPPDATA is defined in the environment, then it is
    assumed to be a directory, and will be the parent directory of the result.
    On POSIX, and on Windows if LOCALAPPDATA is not defined, the user's home
    directory - using os.expanduser('~') - will be the parent directory of
    the result.

    The result is just the directory '.distlib' in the parent directory as
    determined above, or with the name specified with ``suffix``.
    """
    if suffix is None:
        suffix = '.distlib'
    if os.name == 'nt' and 'LOCALAPPDATA' in os.environ:
        result = os.path.expandvars('$localappdata')
    else:
        # Assume posix, or old Windows
        result = os.path.expanduser('~')
    # we use 'isdir' instead of 'exists', because we want to
    # fail if there's a file with that name
    if os.path.isdir(result):
        usable = os.access(result, os.W_OK)
        if not usable:
            logger.warning('Directory exists but is not writable: %s', result)
    else:
        try:
            os.makedirs(result)
            usable = True
        except OSError:
            logger.warning('Unable to create %s', result, exc_info=True)
            usable = False
    if not usable:
        result = tempfile.mkdtemp()
        logger.warning('Default location unusable, using %s', result)
    return os.path.join(result, suffix) 
Example 59
Project: tmanager   Author: ssh3ll   File: file_system.py    MIT License 5 votes vote down vote up
def is_writable(pathname: str) -> bool:
    """
    Returns True if the given file/directory exists and is writable, otherwise returns False.

    :param str pathname:
    :return bool:
    """
    if os.access(pathname, os.W_OK):
        return True

    return False 
Example 60
Project: tmanager   Author: ssh3ll   File: file_system.py    MIT License 5 votes vote down vote up
def is_readable(pathname: str) -> bool:
    """
        Returns True if the given pathname is a readable filename, otherwise returns False.

    :param pathname:
    :return:
    """
    if os.path.isfile(pathname) and os.access(pathname, os.R_OK):
        return True
    return False 
Example 61
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 62
Project: micropython-barebones   Author: reapzor   File: path.py    MIT License 5 votes vote down vote up
def exists(path):
    return os.access(path, os.F_OK)

# TODO 
Example 63
Project: micropython-barebones   Author: reapzor   File: path.py    MIT License 5 votes vote down vote up
def exists(path):
    return os.access(path, os.F_OK)

# TODO 
Example 64
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 65
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    MIT License 5 votes vote down vote up
def extraction_error(self):
        """Give an error message for problems extracting file(s)"""

        old_exc = sys.exc_info()[1]
        cache_path = self.extraction_path or get_default_cache()

        tmpl = textwrap.dedent("""
            Can't extract file(s) to egg cache

            The following error occurred while trying to extract file(s) to the Python egg
            cache:

              {old_exc}

            The Python egg cache directory is currently set to:

              {cache_path}

            Perhaps your account does not have write access to this directory?  You can
            change the cache directory by setting the PYTHON_EGG_CACHE environment
            variable to point to an accessible directory.
            """).lstrip()
        err = ExtractionError(tmpl.format(**locals()))
        err.manager = self
        err.cache_path = cache_path
        err.original_error = old_exc
        raise err 
Example 66
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    MIT License 5 votes vote down vote up
def extraction_error(self):
        """Give an error message for problems extracting file(s)"""

        old_exc = sys.exc_info()[1]
        cache_path = self.extraction_path or get_default_cache()

        tmpl = textwrap.dedent("""
            Can't extract file(s) to egg cache

            The following error occurred while trying to extract file(s) to the Python egg
            cache:

              {old_exc}

            The Python egg cache directory is currently set to:

              {cache_path}

            Perhaps your account does not have write access to this directory?  You can
            change the cache directory by setting the PYTHON_EGG_CACHE environment
            variable to point to an accessible directory.
            """).lstrip()
        err = ExtractionError(tmpl.format(**locals()))
        err.manager = self
        err.cache_path = cache_path
        err.original_error = old_exc
        raise err 
Example 67
Project: AshsSDK   Author: thehappydinoa   File: util.py    MIT License 5 votes vote down vote up
def is_writable(self, path):
        result = False
        while not result:
            if os.path.exists(path):
                result = os.access(path, os.W_OK)
                break
            parent = os.path.dirname(path)
            if parent == path:
                break
            path = parent
        return result 
Example 68
Project: fs_image   Author: facebookincubator   File: compiler.py    MIT License 4 votes vote down vote up
def build_image(args):
    # We want check the umask since it can affect the result of the
    # `os.access` check for `image.install*` items.  That said, having a
    # umask that denies execute permission to "user" is likely to break this
    # code earlier, since new directories wouldn't be traversible.  At least
    # this check gives a nice error message.
    cur_umask = os.umask(0)
    os.umask(cur_umask)
    assert cur_umask & stat.S_IXUSR == 0, \
        f'Refusing to run with pathological umask 0o{cur_umask:o}'

    subvol = Subvol(os.path.join(args.subvolumes_dir, args.subvolume_rel_path))
    layer_opts = LayerOpts(
        layer_target=args.child_layer_target,
        build_appliance=get_subvolume_path(
            args.build_appliance_json, args.subvolumes_dir,
        ) if args.build_appliance_json else None,
        force_yum_dnf=None,  # This is currently only used in `test-items`
        preserve_yum_dnf_cache=args.preserve_yum_dnf_cache,
        artifacts_may_require_repo=args.artifacts_may_require_repo,
        target_to_path=make_target_path_map(args.child_dependencies),
        subvolumes_dir=args.subvolumes_dir,
    )

    # This stack allows build items to hold temporary state on disk.
    with ExitStack() as exit_stack:
        dep_graph = DependencyGraph(gen_items_for_features(
            exit_stack=exit_stack,
            features_or_paths=args.child_feature_json,
            layer_opts=layer_opts,
        ), layer_target=args.child_layer_target)
        # Creating all the builders up-front lets phases validate their input
        for builder in [
            builder_maker(items, layer_opts)
                for builder_maker, items in dep_graph.ordered_phases()
        ]:
            builder(subvol)
        # We cannot validate or sort `ImageItem`s until the phases are
        # materialized since the items may depend on the output of the phases.
        for item in dep_graph.gen_dependency_order_items(PhasesProvideItem(
            from_target=args.child_layer_target,
            subvol=subvol,
        )):
            item.build(subvol, layer_opts)
        # Build artifacts should never change. Run this BEFORE the exit_stack
        # cleanup to enforce that the cleanup does not touch the image.
        subvol.set_readonly(True)

    try:
        return SubvolumeOnDisk.from_subvolume_path(
            # Converting to a path here does not seem too risky since this
            # class shouldn't have a reason to follow symlinks in the subvol.
            subvol.path().decode(),
            args.subvolumes_dir,
        )
    # The complexity of covering this is high, but the only thing that can
    # go wrong is a typo in the f-string.
    except Exception as ex:  # pragma: no cover
        raise RuntimeError(f'Serializing subvolume {subvol.path()}') from ex 
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: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_stat_attributes(self):
        import stat
        result = os.stat(self.fname)

        # Make sure direct access works
        self.assertEqual(result[stat.ST_SIZE], 3)
        self.assertEqual(result.st_size, 3)

        # Make sure all the attributes are there
        members = dir(result)
        for name in dir(stat):
            if name[:3] == 'ST_':
                attr = name.lower()
                if name.endswith("TIME"):
                    def trunc(x): return int(x)
                else:
                    def trunc(x): return x
                self.assertEqual(trunc(getattr(result, attr)),
                                 result[getattr(stat, name)])
                self.assertIn(attr, members)

        try:
            result[200]
            self.fail("No exception raised")
        except IndexError:
            pass

        # Make sure that assignment fails
        try:
            result.st_mode = 1
            self.fail("No exception raised")
        except (AttributeError, TypeError):
            pass

        try:
            result.st_rdev = 1
            self.fail("No exception raised")
        except (AttributeError, TypeError):
            pass

        try:
            result.parrot = 1
            self.fail("No exception raised")
        except AttributeError:
            pass

        # Use the stat_result constructor with a too-short tuple.
        try:
            result2 = os.stat_result((10,))
            self.fail("No exception raised")
        except TypeError:
            pass

        # Use the constructor with a too-long tuple.
        try:
            result2 = os.stat_result((0,1,2,3,4,5,6,7,8,9,10,11,12,13,14))
        except TypeError:
            pass 
Example 71
Project: pyblish-win   Author: pyblish   File: test_os.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def _kill(self, sig):
        # Start sys.executable as a subprocess and communicate from the
        # subprocess to the parent that the interpreter is ready. When it
        # becomes ready, send *sig* via os.kill to the subprocess and check
        # that the return code is equal to *sig*.
        import ctypes
        from ctypes import wintypes
        import msvcrt

        # Since we can't access the contents of the process' stdout until the
        # process has exited, use PeekNamedPipe to see what's inside stdout
        # without waiting. This is done so we can tell that the interpreter
        # is started and running at a point where it could handle a signal.
        PeekNamedPipe = ctypes.windll.kernel32.PeekNamedPipe
        PeekNamedPipe.restype = wintypes.BOOL
        PeekNamedPipe.argtypes = (wintypes.HANDLE, # Pipe handle
                                  ctypes.POINTER(ctypes.c_char), # stdout buf
                                  wintypes.DWORD, # Buffer size
                                  ctypes.POINTER(wintypes.DWORD), # bytes read
                                  ctypes.POINTER(wintypes.DWORD), # bytes avail
                                  ctypes.POINTER(wintypes.DWORD)) # bytes left
        msg = "running"
        proc = subprocess.Popen([sys.executable, "-c",
                                 "import sys;"
                                 "sys.stdout.write('{}');"
                                 "sys.stdout.flush();"
                                 "input()".format(msg)],
                                stdout=subprocess.PIPE,
                                stderr=subprocess.PIPE,
                                stdin=subprocess.PIPE)
        self.addCleanup(proc.stdout.close)
        self.addCleanup(proc.stderr.close)
        self.addCleanup(proc.stdin.close)

        count, max = 0, 100
        while count < max and proc.poll() is None:
            # Create a string buffer to store the result of stdout from the pipe
            buf = ctypes.create_string_buffer(len(msg))
            # Obtain the text currently in proc.stdout
            # Bytes read/avail/left are left as NULL and unused
            rslt = PeekNamedPipe(msvcrt.get_osfhandle(proc.stdout.fileno()),
                                 buf, ctypes.sizeof(buf), None, None, None)
            self.assertNotEqual(rslt, 0, "PeekNamedPipe failed")
            if buf.value:
                self.assertEqual(msg, buf.value)
                break
            time.sleep(0.1)
            count += 1
        else:
            self.fail("Did not receive communication from the subprocess")

        os.kill(proc.pid, sig)
        self.assertEqual(proc.wait(), sig) 
Example 72
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: uri.py    MIT License 4 votes vote down vote up
def write_file(module, url, dest, content):
    # create a tempfile with some test content
    fd, tmpsrc = tempfile.mkstemp(dir=getattr(module, 'tmpdir', None))
    f = open(tmpsrc, 'wb')
    try:
        f.write(content)
    except Exception as e:
        os.remove(tmpsrc)
        module.fail_json(msg="failed to create temporary content file: %s" % to_native(e),
                         exception=traceback.format_exc())
    f.close()

    checksum_src = None
    checksum_dest = None

    # raise an error if there is no tmpsrc file
    if not os.path.exists(tmpsrc):
        os.remove(tmpsrc)
        module.fail_json(msg="Source '%s' does not exist" % tmpsrc)
    if not os.access(tmpsrc, os.R_OK):
        os.remove(tmpsrc)
        module.fail_json(msg="Source '%s' not readable" % tmpsrc)
    checksum_src = module.sha1(tmpsrc)

    # check if there is no dest file
    if os.path.exists(dest):
        # raise an error if copy has no permission on dest
        if not os.access(dest, os.W_OK):
            os.remove(tmpsrc)
            module.fail_json(msg="Destination '%s' not writable" % dest)
        if not os.access(dest, os.R_OK):
            os.remove(tmpsrc)
            module.fail_json(msg="Destination '%s' not readable" % dest)
        checksum_dest = module.sha1(dest)
    else:
        if not os.access(os.path.dirname(dest), os.W_OK):
            os.remove(tmpsrc)
            module.fail_json(msg="Destination dir '%s' not writable" % os.path.dirname(dest))

    if checksum_src != checksum_dest:
        try:
            shutil.copyfile(tmpsrc, dest)
        except Exception as e:
            os.remove(tmpsrc)
            module.fail_json(msg="failed to copy %s to %s: %s" % (tmpsrc, dest, to_native(e)),
                             exception=traceback.format_exc())

    os.remove(tmpsrc) 
Example 73
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: vmware_guest_file_operation.py    MIT License 4 votes vote down vote up
def copy(self):
        result = dict(changed=True, uuid=self.vm.summary.config.uuid)
        vm_username = self.module.params['vm_username']
        vm_password = self.module.params['vm_password']
        overwrite = self.module.params["copy"]["overwrite"]
        dest = self.module.params["copy"]['dest']
        src = self.module.params['copy']['src']
        b_src = to_bytes(src, errors='surrogate_or_strict')

        if not os.path.exists(b_src):
            self.module.fail_json(msg="Source %s not found" % src)
        if not os.access(b_src, os.R_OK):
            self.module.fail_json(msg="Source %s not readable" % src)
        if os.path.isdir(b_src):
            self.module.fail_json(msg="copy does not support copy of directory: %s" % src)

        data = None
        with open(b_src, "r") as local_file:
            data = local_file.read()
        file_size = os.path.getsize(b_src)

        creds = vim.vm.guest.NamePasswordAuthentication(username=vm_username, password=vm_password)
        file_attributes = vim.vm.guest.FileManager.FileAttributes()
        file_manager = self.content.guestOperationsManager.fileManager
        try:
            url = file_manager.InitiateFileTransferToGuest(vm=self.vm, auth=creds, guestFilePath=dest,
                                                           fileAttributes=file_attributes, overwrite=overwrite,
                                                           fileSize=file_size)
            resp, info = urls.fetch_url(self.module, url, data=data, method="PUT")

            status_code = info["status"]
            if status_code != 200:
                self.module.fail_json(msg='initiateFileTransferToGuest : problem during file transfer',
                                      uuid=self.vm.summary.config.uuid)
        except vim.fault.FileAlreadyExists:
            result['changed'] = False
            result['msg'] = "Guest file %s already exists" % dest
            return result
        except vim.fault.FileFault as e:
            self.module.fail_json(msg="FileFault:%s" % to_native(e.msg),
                                  uuid=self.vm.summary.config.uuid)
        except vim.fault.GuestPermissionDenied as permission_denied:
            self.module.fail_json(msg="Permission denied to copy file into "
                                      "destination %s : %s" % (dest, to_native(permission_denied.msg)),
                                  uuid=self.vm.summary.config.uuid)
        except vim.fault.InvalidGuestLogin as invalid_guest_login:
            self.module.fail_json(msg="Invalid guest login for user"
                                      " %s : %s" % (vm_username, to_native(invalid_guest_login.msg)))
        # other exceptions
        except Exception as e:
            self.module.fail_json(msg="Failed to Copy file to Vm VMware exception : %s" % to_native(e),
                                  uuid=self.vm.summary.config.uuid)
        return result 
Example 74
Project: Ansible-Example-AB2018   Author: umit-ozturk   File: patch.py    MIT License 4 votes vote down vote up
def main():
    module = AnsibleModule(
        argument_spec=dict(
            src=dict(type='path', required=True, aliases=['patchfile']),
            dest=dict(type='path', aliases=['originalfile']),
            basedir=dict(type='path'),
            strip=dict(type='int', default=0),
            remote_src=dict(type='bool', default=False),
            # NB: for 'backup' parameter, semantics is slightly different from standard
            #     since patch will create numbered copies, not strftime("%Y-%m-%[email protected]%H:%M:%S~")
            backup=dict(type='bool', default=False),
            binary=dict(type='bool', default=False),
        ),
        required_one_of=[['dest', 'basedir']],
        supports_check_mode=True,
    )

    # Create type object as namespace for module params
    p = type('Params', (), module.params)

    if not os.access(p.src, os.R_OK):
        module.fail_json(msg="src %s doesn't exist or not readable" % (p.src))

    if p.dest and not os.access(p.dest, os.W_OK):
        module.fail_json(msg="dest %s doesn't exist or not writable" % (p.dest))

    if p.basedir and not os.path.exists(p.basedir):
        module.fail_json(msg="basedir %s doesn't exist" % (p.basedir))

    if not p.basedir:
        p.basedir = os.path.dirname(p.dest)

    patch_bin = module.get_bin_path('patch')
    if patch_bin is None:
        module.fail_json(msg="patch command not found")

    def patch_func(opts):
        return module.run_command('%s %s' % (patch_bin, ' '.join(opts)))

    # patch need an absolute file name
    p.src = os.path.abspath(p.src)

    changed = False
    if not is_already_applied(patch_func, p.src, p.basedir, dest_file=p.dest, binary=p.binary, strip=p.strip):
        try:
            apply_patch(patch_func, p.src, p.basedir, dest_file=p.dest, binary=p.binary, strip=p.strip,
                        dry_run=module.check_mode, backup=p.backup)
            changed = True
        except PatchError as e:
            module.fail_json(msg=to_native(e), exception=format_exc())

    module.exit_json(changed=changed) 
Example 75
Project: sic   Author: Yanixos   File: tempfile.py    GNU General Public License v3.0 4 votes vote down vote up
def _get_default_tempdir():
    """Calculate the default directory to use for temporary files.
    This routine should be called exactly once.

    We determine whether or not a candidate temp dir is usable by
    trying to create and write to a file in that directory.  If this
    is successful, the test file is deleted.  To prevent denial of
    service, the name of the test file must be randomized."""

    namer = _RandomNameSequence()
    dirlist = _candidate_tempdir_list()

    for dir in dirlist:
        if dir != _os.curdir:
            dir = _os.path.abspath(dir)
        # Try only a few names per directory.
        for seq in range(100):
            name = next(namer)
            filename = _os.path.join(dir, name)
            try:
                fd = _os.open(filename, _bin_openflags, 0o600)
                try:
                    try:
                        with _io.open(fd, 'wb', closefd=False) as fp:
                            fp.write(b'blat')
                    finally:
                        _os.close(fd)
                finally:
                    _os.unlink(filename)
                return dir
            except FileExistsError:
                pass
            except PermissionError:
                # This exception is thrown when a directory with the chosen name
                # already exists on windows.
                if (_os.name == 'nt' and _os.path.isdir(dir) and
                    _os.access(dir, _os.W_OK)):
                    continue
                break   # no point trying more names in this directory
            except OSError:
                break   # no point trying more names in this directory
    raise FileNotFoundError(_errno.ENOENT,
                            "No usable temporary directory found in %s" %
                            dirlist) 
Example 76
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 77
Project: sic   Author: Yanixos   File: __init__.py    GNU General Public License v3.0 4 votes vote down vote up
def find_on_path(importer, path_item, only=False):
    """Yield distributions accessible on a sys.path directory"""
    path_item = _normalize_cached(path_item)

    if os.path.isdir(path_item) and os.access(path_item, os.R_OK):
        if _is_unpacked_egg(path_item):
            yield Distribution.from_filename(
                path_item, metadata=PathMetadata(
                    path_item, os.path.join(path_item, 'EGG-INFO')
                )
            )
        else:
            # scan for .egg and .egg-info in directory
            path_item_entries = _by_version_descending(os.listdir(path_item))
            for entry in path_item_entries:
                lower = entry.lower()
                if lower.endswith('.egg-info') or lower.endswith('.dist-info'):
                    fullpath = os.path.join(path_item, entry)
                    if os.path.isdir(fullpath):
                        # egg-info directory, allow getting metadata
                        if len(os.listdir(fullpath)) == 0:
                            # Empty egg directory, skip.
                            continue
                        metadata = PathMetadata(path_item, fullpath)
                    else:
                        metadata = FileMetadata(fullpath)
                    yield Distribution.from_location(
                        path_item, entry, metadata, precedence=DEVELOP_DIST
                    )
                elif not only and _is_unpacked_egg(entry):
                    dists = find_distributions(os.path.join(path_item, entry))
                    for dist in dists:
                        yield dist
                elif not only and lower.endswith('.egg-link'):
                    with open(os.path.join(path_item, entry)) as entry_file:
                        entry_lines = entry_file.readlines()
                    for line in entry_lines:
                        if not line.strip():
                            continue
                        path = os.path.join(path_item, line.rstrip())
                        dists = find_distributions(path)
                        for item in dists:
                            yield item
                        break 
Example 78
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 79
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    MIT License 4 votes vote down vote up
def find_on_path(importer, path_item, only=False):
    """Yield distributions accessible on a sys.path directory"""
    path_item = _normalize_cached(path_item)

    if os.path.isdir(path_item) and os.access(path_item, os.R_OK):
        if _is_unpacked_egg(path_item):
            yield Distribution.from_filename(
                path_item, metadata=PathMetadata(
                    path_item, os.path.join(path_item, 'EGG-INFO')
                )
            )
        else:
            # scan for .egg and .egg-info in directory
            path_item_entries = _by_version_descending(os.listdir(path_item))
            for entry in path_item_entries:
                lower = entry.lower()
                if lower.endswith('.egg-info') or lower.endswith('.dist-info'):
                    fullpath = os.path.join(path_item, entry)
                    if os.path.isdir(fullpath):
                        # egg-info directory, allow getting metadata
                        if len(os.listdir(fullpath)) == 0:
                            # Empty egg directory, skip.
                            continue
                        metadata = PathMetadata(path_item, fullpath)
                    else:
                        metadata = FileMetadata(fullpath)
                    yield Distribution.from_location(
                        path_item, entry, metadata, precedence=DEVELOP_DIST
                    )
                elif not only and _is_egg_path(entry):
                    dists = find_distributions(os.path.join(path_item, entry))
                    for dist in dists:
                        yield dist
                elif not only and lower.endswith('.egg-link'):
                    with open(os.path.join(path_item, entry)) as entry_file:
                        entry_lines = entry_file.readlines()
                    for line in entry_lines:
                        if not line.strip():
                            continue
                        path = os.path.join(path_item, line.rstrip())
                        dists = find_distributions(path)
                        for item in dists:
                            yield item
                        break 
Example 80
Project: AshsSDK   Author: thehappydinoa   File: __init__.py    MIT License 4 votes vote down vote up
def find_on_path(importer, path_item, only=False):
    """Yield distributions accessible on a sys.path directory"""
    path_item = _normalize_cached(path_item)

    if os.path.isdir(path_item) and os.access(path_item, os.R_OK):
        if _is_unpacked_egg(path_item):
            yield Distribution.from_filename(
                path_item, metadata=PathMetadata(
                    path_item, os.path.join(path_item, 'EGG-INFO')
                )
            )
        else:
            # scan for .egg and .egg-info in directory
            path_item_entries = _by_version_descending(os.listdir(path_item))
            for entry in path_item_entries:
                lower = entry.lower()
                if lower.endswith('.egg-info') or lower.endswith('.dist-info'):
                    fullpath = os.path.join(path_item, entry)
                    if os.path.isdir(fullpath):
                        # egg-info directory, allow getting metadata
                        if len(os.listdir(fullpath)) == 0:
                            # Empty egg directory, skip.
                            continue
                        metadata = PathMetadata(path_item, fullpath)
                    else:
                        metadata = FileMetadata(fullpath)
                    yield Distribution.from_location(
                        path_item, entry, metadata, precedence=DEVELOP_DIST
                    )
                elif not only and _is_unpacked_egg(entry):
                    dists = find_distributions(os.path.join(path_item, entry))
                    for dist in dists:
                        yield dist
                elif not only and lower.endswith('.egg-link'):
                    with open(os.path.join(path_item, entry)) as entry_file:
                        entry_lines = entry_file.readlines()
                    for line in entry_lines:
                        if not line.strip():
                            continue
                        path = os.path.join(path_item, line.rstrip())
                        dists = find_distributions(path)
                        for item in dists:
                            yield item
                        break