Python os.access() Examples

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

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

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

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

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

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

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

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

    return '' 
Example 2
Project: PickTrue   Author: winkidney   File: downloader.py    License: 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 3
Project: PickTrue   Author: winkidney   File: downloader.py    License: 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 4
Project: EXOSIMS   Author: dsavransky   File: get_dirs.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_cache_dir(cachedir=None):
    """
    Return EXOSIMS cache directory.  Order of priority is:
    1. Input (typically taken from JSON spec script)
    2. EXOSIMS_CACHE_DIR environment variable
    3. Default in $HOME/.EXOSIMS/cache (for whatever $HOME is returned by get_home_dir)

    In each case, the directory is checked for read/write/access permissions.  If 
    any permissions are missing, will return default path.

    Returns:
        cache_dir (str):
            Path to EXOSIMS cache directory
    """

    cache_dir = get_exosims_dir('cache',cachedir)
    return cache_dir 
Example 5
Project: EXOSIMS   Author: dsavransky   File: get_dirs.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def get_downloads_dir(downloadsdir=None):
    """
    Return EXOSIMS downloads directory.  Order of priority is:
    1. Input (typically taken from JSON spec script)
    2. EXOSIMS_CACHE_DIR environment variable
    3. Default in $HOME/.EXOSIMS/downloads (for whatever $HOME is returned by get_home_dir)

    In each case, the directory is checked for read/write/access permissions.  If 
    any permissions are missing, will return default path.


    Returns:
        downloads_dir (str):
            Path to EXOSIMS downloads directory
    """

    downloads_dir = get_exosims_dir('downloads',downloadsdir)

    return downloads_dir 
Example 6
Project: EXOSIMS   Author: dsavransky   File: Forecaster.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def __init__(self, n_pop=4, **specs):
        
        FortneyMarleyCahoyMix1.__init__(self, **specs)
        
        # number of category
        self.n_pop = int(n_pop)
        
        # read forecaster parameter file
        downloadsdir = get_downloads_dir()
        filename = 'fitting_parameters.h5'
        parampath = os.path.join(downloadsdir, filename)
        if not os.path.exists(parampath) and os.access(downloadsdir, os.W_OK|os.X_OK):
            fitting_url = 'https://raw.github.com/dsavransky/forecaster/master/fitting_parameters.h5'
            self.vprint("Fetching Forecaster fitting parameters from %s to %s" % (fitting_url, parampath))
            try:
                urlretrieve(fitting_url, parampath)
            except:
                self.vprint("Error: Remote fetch failed. Fetch manually or see install instructions.")

        assert os.path.exists(parampath), 'fitting_parameters.h5 must exist in /.EXOSIMS/downloads'

        h5 = h5py.File(parampath, 'r')
        self.all_hyper = h5['hyper_posterior'][:]
        h5.close() 
Example 7
Project: ciftify   Author: edickie   File: ciftify_vol_result.py    License: MIT License 6 votes vote down vote up
def get_output_filename(self, user_outputname):
        '''
        check that we have permissions to write to output directory
        adds 'dscalar.nii' to end of outputname if not already present
        '''
        outputname = os.path.realpath(user_outputname)
        output_dir = os.path.dirname(outputname)
        if not os.access(output_dir, os.W_OK):
            logger.error('Cannot write to output file {}\n'\
                         'The folder does not exist, or you do not have permission to write there'\
                         ''.format(outputname))
            sys.exit(1)
        if not outputname.endswith('dscalar.nii'):
            if not outputname.endswith('dtseries.nii'):
                logger.info("Appending '.dscalar.nii' extension to outputname")
                outputname = '{}.dscalar.nii'.format(outputname)
        return outputname 
Example 8
Project: razzy-spinner   Author: rafasashi   File: chat80.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, prefLabel, arity, altLabels=[], closures=[], extension=set()):
        """
        :param prefLabel: the preferred label for the concept
        :type prefLabel: str
        :param arity: the arity of the concept
        :type arity: int
        @keyword altLabels: other (related) labels
        :type altLabels: list
        @keyword closures: closure properties of the extension \
            (list items can be ``symmetric``, ``reflexive``, ``transitive``)
        :type closures: list
        @keyword extension: the extensional value of the concept
        :type extension: set
        """
        self.prefLabel = prefLabel
        self.arity = arity
        self.altLabels = altLabels
        self.closures = closures
        #keep _extension internally as a set
        self._extension = extension
        #public access is via a list (for slicing)
        self.extension = sorted(list(extension)) 
Example 9
Project: LGWebOSRemote   Author: klattimer   File: __init__.py    License: MIT License 6 votes vote down vote up
def find_config():
    w = None
    for f in search_config:
        f = os.path.expanduser(f)
        f = os.path.abspath(f)
        d = os.path.dirname(f)
        if os.path.exists(d):
            if os.access(d, os.W_OK):
                w = f
            if os.path.exists(f):
                if os.access(f, os.W_OK):
                    return f
        elif os.access(os.path.dirname(d), os.W_OK):
            os.makedirs(d)
            w = f
    if w is None:
        print ("Cannot find suitable config path to write, create one in %s" % ' or '.join(search_config))
        raise Exception("No config file")
    return w 
Example 10
Project: py-solc   Author: ethereum   File: install_solc.py    License: MIT License 6 votes vote down vote up
def is_executable_available(program):
    def is_exe(fpath):
        return os.path.isfile(fpath) and os.access(fpath, os.X_OK)

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

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

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

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

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

    return False 
Example 13
Project: core   Author: getavalon   File: lib.py    License: MIT License 6 votes vote down vote up
def which(program):
    """Locate `program` in PATH

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

    """

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

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

            if is_exe(abspath):
                return abspath

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

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

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

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

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

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

    return None 
Example 16
Project: JetPack   Author: dsp-jetpack   File: deploy-dashboard-vm.py    License: Apache License 2.0 6 votes vote down vote up
def create_floppy_image(vlock_filename, floppy_image):
    """ Creates the floppy image used to install the vlock file
    """

    # Delete any existing image to start clean
    if os.access(floppy_image, os.R_OK):
        os.unlink(floppy_image)

    subprocess.check_call("mkfs.vfat -C {} 1440".format(floppy_image),
                          shell=True)

    floppy_mnt = "/tmp/mnt-dashboard"
    os.mkdir(floppy_mnt)

    subprocess.check_call("mount -o loop {} {}".format(floppy_image,
                                                       floppy_mnt),
                          shell=True)

    shutil.copy(vlock_filename, os.path.join(floppy_mnt, "versionlock.list"))

    subprocess.check_call("umount {}".format(floppy_mnt), shell=True)
    os.rmdir(floppy_mnt) 
Example 17
Project: droidlysis   Author: cryptax   File: droidsample.py    License: MIT License 6 votes vote down vote up
def extract_file_properties(self):
        """Extracts file size, 
        nb of dirs and classes in smali dir"""
        if self.verbose:
            print("------------- Extracting file properties")
            
        self.properties.file_size = os.stat(self.absolute_filename).st_size

        if self.properties.file_size < 70000:
            self.properties.file_small = True
        
        smali_dir = os.path.join(self.outdir, "smali")

        if os.access(smali_dir, os.R_OK):
            self.properties.file_nb_dir, self.properties.file_nb_classes = droidutil.count_filedirs(smali_dir)

        if self.verbose:
            print( "Filesize: %d" % (self.properties.file_size))
            print( "Is Small: %d" % (self.properties.file_small))
            print( "Nb Class: %d" % (self.properties.file_nb_classes))
            print( "Nb Dir  : %d" % (self.properties.file_nb_dir)) 
Example 18
Project: droidlysis   Author: cryptax   File: droidsample.py    License: MIT License 6 votes vote down vote up
def extract_kit_properties(self):
        """
        Detects which kits are present in the sample currently analyzed
        Returns something like: ['apperhand', 'jackson', 'applovin', 'leadbolt', 'airpush']
        """
        list = []
        if self.properties.filetype == droidutil.APK or self.properties.filetype == droidutil.DEX:
            smali_dir = os.path.join(self.outdir, "smali")
            if os.access(smali_dir, os.R_OK):
                for section in self.properties.kitsconfig.get_sections():
                    pattern_list = self.properties.kitsconfig.get_pattern(section).split('|')
                    for pattern in pattern_list:
                        if os.access(os.path.join(smali_dir, pattern), os.R_OK):
                            if self.verbose:
                                print("kits[%s] = True (detected pattern: %s)" % (section, pattern))
                            list.append(section)
                            self.properties.kits[ section ] = True
                            break # break one level
        return list 
Example 19
Project: yatsm   Author: ceholden   File: options.py    License: MIT License 6 votes vote down vote up
def opt_exampleimg(f):
    def callback(ctx, param, value):
        # Check if file qualifies alone
        if os.path.isfile(value):
            _value = value
        else:
            # Check if path relative to root qualifies
            _value = os.path.join(ctx.params['root'], value)
            if not os.path.isfile(_value):
                raise click.BadParameter('Cannot find example image '
                                         '"{f}"'.format(f=value))
            if not os.access(_value, os.R_OK):
                raise click.BadParameter('Found example image but cannot '
                                         'read from "{f}"'.format(f=_value))
        return os.path.abspath(_value)
    return click.option('--image', '-i',
                        default='example_img',
                        metavar='<image>',
                        show_default=True,
                        help='Example timeseries image',
                        callback=callback)(f) 
Example 20
Project: yatsm   Author: ceholden   File: options.py    License: MIT License 6 votes vote down vote up
def opt_resultdir(f):
    def callback(ctx, param, value):
        # Check if path qualifies alone
        if os.path.isdir(value):
            _value = value
        else:
            # Check if path relative to root qualifies
            _value = os.path.join(ctx.params['root'], value)
            if not os.path.isdir(_value):
                raise click.BadParameter('Cannot find result directory '
                                         '"{d}"'.format(d=value))
        if not os.access(_value, os.R_OK):
            raise click.BadParameter('Found result directory but cannot '
                                     'read from "{d}"'.format(d=_value))
        return os.path.abspath(_value)
    return click.option('--result', '-r',
                        default='YATSM',
                        metavar='<directory>',
                        show_default=True,
                        help='Directory of results',
                        callback=callback)(f)


# CALLBACKS 
Example 21
Project: multibootusb   Author: mbusb   File: iso.py    License: GNU General Public License v2.0 5 votes vote down vote up
def is_readable(iso_link):
    return os.access(iso_link, os.R_OK) 
Example 22
Project: multibootusb   Author: mbusb   File: syslinux.py    License: GNU General Public License v2.0 5 votes vote down vote up
def linux_install_default_bootsector(usb_disk, mbr_install_cmd):

    with usb.UnmountedContext(usb_disk, config.update_usb_mount):
        syslinux_cmd = [syslinux_path, '-i', '-d', 'multibootusb', usb_disk]
        if os.access(syslinux_path, os.X_OK) is False:
            subprocess.call('chmod +x ' + syslinux_path, shell=True)
        log("\nExecuting ==> %s\n" % syslinux_cmd)
        config.status_text = 'Installing default syslinux version 4...'
        if subprocess.call(syslinux_cmd) == 0:

            # On my system, it takes hours long to complete a single check
            # So not included as of now
            # usb.repair_vfat_filesystem(usb_disk)

            log("\nDefault syslinux install is success...\n")
            config.status_text = 'Default syslinux successfully installed...'
            log('\nExecuting ==> ' + mbr_install_cmd)
            if subprocess.call(mbr_install_cmd, shell=True) == 0:
                config.status_text = 'mbr install is success...'
                log("\nmbr install is success...\n")
                if set_boot_flag(usb_disk) is True:
                    return True
                else:
                    log("\nFailed to install default syslinux...\n")
                    config.status_text = 'Failed to install default syslinux...'
                    return False
    return None 
Example 23
Project: multibootusb   Author: mbusb   File: syslinux.py    License: GNU General Public License v2.0 5 votes vote down vote up
def build_distro_bootsector_impl(usb_disk, options,
                                 distro_syslinux_install_dir):
    syslinux_path = os.path.join(
        multibootusb_host_dir(), "syslinux", "bin", "syslinux") \
        + config.syslinux_version

    if os.access(syslinux_path, os.X_OK) is False:
        subprocess.call('chmod +x ' + syslinux_path, shell=True)
    sys_cmd = [syslinux_path] + options + [
        distro_syslinux_install_dir, usb_disk]
    log("Executing ==> %s" % sys_cmd)
    if subprocess.call(sys_cmd) == 0:
        config.status_text = \
            'Syslinux install on distro directory is successful...'
        log("\nSyslinux install on distro directory is successful...\n")

        # On my system, it takes hours long to complete a single check
        # So not included as of now
        # usb.repair_vfat_filesystem(usb_disk)

        tmp_bs_file = '/tmp/mbusb_temp.bs'
        dd_cmd = ['dd', 'if=' + usb_disk, 'of=' + tmp_bs_file, 'count=1']
        log('Executing ==> %s' % dd_cmd + '\n')
        config.status_text = 'Copying boot sector...'
        config.status_text = 'Installing distro specific syslinux...'
        if subprocess.call(dd_cmd) == 0:
            config.status_text = 'Bootsector copy is successful...'
            log("\nBootsector copy is successful...\n")
        else:
            config.status_text = 'Failed to copy boot sector...'
            log("\nFailed to copy boot sector...\n")
        return tmp_bs_file
    else:
        config.status_text = 'Failed to install syslinux on distro directory...'
        log("\nFailed to install syslinux on distro directory...\n")
        return None 
Example 24
Project: numpynet   Author: uptake   File: loggit.py    License: 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 25
Project: PickTrue   Author: winkidney   File: downloader.py    License: 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 26
Project: mx   Author: graalvm   File: mx_fetchjdk.py    License: GNU General Public License v2.0 5 votes vote down vote up
def check_write_access(path):
    try:
        if not exists(path):
            os.makedirs(path)
        if not os.access(path, os.W_OK):
            raise IOError
        return True
    except (IOError, OSError):
        return False 
Example 27
Project: mx   Author: graalvm   File: select_jdk.py    License: GNU General Public License v2.0 5 votes vote down vote up
def is_valid_jdk(jdk):
    """
    Determines if `jdk` looks like a valid JDK directory.

    :return: True if there's a ``java`` executable in ``jdk/bin``
    """
    java_exe = join(jdk, 'bin', 'java')
    if not exists(java_exe):
        java_exe += '.exe'
    return isfile(java_exe) and os.access(java_exe, os.X_OK) 
Example 28
Project: script.module.inputstreamhelper   Author: emilsvennesson   File: widevine.py    License: MIT License 5 votes vote down vote up
def missing_widevine_libs():
    """Parses ldd output of libwidevinecdm.so and displays dialog if any depending libraries are missing."""
    if system_os() != 'Linux':  # this should only be needed for linux
        return None

    if cmd_exists('ldd'):
        widevinecdm = widevinecdm_path()
        if not os.access(widevinecdm, os.X_OK):
            log(0, 'Changing {path} permissions to 744.', path=widevinecdm)
            os.chmod(widevinecdm, 0o744)

        missing_libs = []
        cmd = ['ldd', widevinecdm]
        output = run_cmd(cmd, sudo=False)
        if output['success']:
            for line in output['output'].splitlines():
                if '=>' not in str(line):
                    continue
                lib_path = str(line).strip().split('=>')
                lib = lib_path[0].strip()
                path = lib_path[1].strip()
                if path == 'not found':
                    missing_libs.append(lib)

            if missing_libs:
                log(4, 'Widevine is missing the following libraries: {libs}', libs=missing_libs)
                return missing_libs

            log(0, 'There are no missing Widevine libraries! :-)')
            return None

    log(4, 'Failed to check for missing Widevine libraries.')
    return None 
Example 29
Project: hacking-tools   Author: girishramnani   File: _pfish_tools.py    License: MIT License 5 votes vote down vote up
def ValidateDirectoryWritable(theDir):
    if not os.path.isdir(theDir):
        raise argparse.ArgumentTypeError("Directory does not exist")
    if os.access(theDir,os.W_OK):
        return theDir
    else:
        raise argparse.ArgumentTypeError("Directory is not writable") 
Example 30
Project: youku   Author: hanguokai   File: youku_upload.py    License: Apache License 2.0 5 votes vote down vote up
def _save_upload_state_to_file(self):
        """if create and create_file has execute, save upload state
        to file for next resume upload if current upload process is
        interrupted.
        """
        if os.access(self.file_dir, os.W_OK | os.R_OK | os.X_OK):
            save_file = self.file + '.upload'
            data = {
                'upload_token': self.upload_token,
                'upload_server_ip': self.upload_server_ip
            }
            with open(save_file, 'w') as f:
                json.dump(data, f)