Python os.F_OK Examples

The following are 30 code examples of os.F_OK(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module os , or try the search function .
Example #1
Source File: uuid.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _popen(command, args):
    import os
    path = os.environ.get("PATH", os.defpath).split(os.pathsep)
    path.extend(('/sbin', '/usr/sbin'))
    for dir in path:
        executable = os.path.join(dir, command)
        if (os.path.exists(executable) and
            os.access(executable, os.F_OK | os.X_OK) and
            not os.path.isdir(executable)):
            break
    else:
        return None
    # LC_ALL to ensure English output, 2>/dev/null to prevent output on
    # stderr (Note: we don't have an example where the words we search for
    # are actually localized, but in theory some system could do so.)
    cmd = 'LC_ALL=C %s %s 2>/dev/null' % (executable, args)
    return os.popen(cmd) 
Example #2
Source File: _pslinux.py    From psutil with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def is_storage_device(name):
    """Return True if the given name refers to a root device (e.g.
    "sda", "nvme0n1") as opposed to a logical partition (e.g.  "sda1",
    "nvme0n1p1"). If name is a virtual device (e.g. "loop1", "ram")
    return True.
    """
    # Readapted from iostat source code, see:
    # https://github.com/sysstat/sysstat/blob/
    #     97912938cd476645b267280069e83b1c8dc0e1c7/common.c#L208
    # Some devices may have a slash in their name (e.g. cciss/c0d0...).
    name = name.replace('/', '!')
    including_virtual = True
    if including_virtual:
        path = "/sys/block/%s" % name
    else:
        path = "/sys/block/%s/device" % name
    return os.access(path, os.F_OK) 
Example #3
Source File: catalog.py    From Computable with MIT License 6 votes vote down vote up
def get_writable_file(self,existing_only=0):
        """ Return the name of the first writable catalog file.

            Its parent directory must also be writable.  This is so that
            compiled modules can be written to the same directory.
        """
        # note: both file and its parent directory must be writeable
        if existing_only:
            files = self.get_existing_files()
        else:
            files = self.get_catalog_files()
        # filter for (file exists and is writable) OR directory is writable

        def file_test(x):
            from os import access, F_OK, W_OK
            return (access(x,F_OK) and access(x,W_OK) or
                    access(os.path.dirname(x),W_OK))
        writable = filter(file_test,files)
        if writable:
            file = writable[0]
        else:
            file = None
        return file 
Example #4
Source File: _pslinux.py    From teleport with Apache License 2.0 6 votes vote down vote up
def is_storage_device(name):
    """Return True if the given name refers to a root device (e.g.
    "sda", "nvme0n1") as opposed to a logical partition (e.g.  "sda1",
    "nvme0n1p1"). If name is a virtual device (e.g. "loop1", "ram")
    return True.
    """
    # Readapted from iostat source code, see:
    # https://github.com/sysstat/sysstat/blob/
    #     97912938cd476645b267280069e83b1c8dc0e1c7/common.c#L208
    # Some devices may have a slash in their name (e.g. cciss/c0d0...).
    name = name.replace('/', '!')
    including_virtual = True
    if including_virtual:
        path = "/sys/block/%s" % name
    else:
        path = "/sys/block/%s/device" % name
    return os.access(path, os.F_OK) 
Example #5
Source File: _pslinux.py    From teleport with Apache License 2.0 6 votes vote down vote up
def is_storage_device(name):
    """Return True if the given name refers to a root device (e.g.
    "sda", "nvme0n1") as opposed to a logical partition (e.g.  "sda1",
    "nvme0n1p1"). If name is a virtual device (e.g. "loop1", "ram")
    return True.
    """
    # Readapted from iostat source code, see:
    # https://github.com/sysstat/sysstat/blob/
    #     97912938cd476645b267280069e83b1c8dc0e1c7/common.c#L208
    # Some devices may have a slash in their name (e.g. cciss/c0d0...).
    name = name.replace('/', '!')
    including_virtual = True
    if including_virtual:
        path = "/sys/block/%s" % name
    else:
        path = "/sys/block/%s/device" % name
    return os.access(path, os.F_OK) 
Example #6
Source File: creation.py    From bioforum with MIT License 6 votes vote down vote up
def _clone_test_db(self, suffix, verbosity, keepdb=False):
        source_database_name = self.connection.settings_dict['NAME']
        target_database_name = self.get_test_db_clone_settings(suffix)['NAME']
        # Forking automatically makes a copy of an in-memory database.
        if not self.is_in_memory_db(source_database_name):
            # Erase the old test database
            if os.access(target_database_name, os.F_OK):
                if keepdb:
                    return
                if verbosity >= 1:
                    print("Destroying old test database for alias %s..." % (
                        self._get_database_display_str(verbosity, target_database_name),
                    ))
                try:
                    os.remove(target_database_name)
                except Exception as e:
                    sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
                    sys.exit(2)
            try:
                shutil.copy(source_database_name, target_database_name)
            except Exception as e:
                sys.stderr.write("Got an error cloning the test database: %s\n" % e)
                sys.exit(2) 
Example #7
Source File: uuid.py    From oss-ftp with MIT License 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 #8
Source File: base.py    From jbox with MIT License 6 votes vote down vote up
def __init__(self, dir, file_template=_default_file_template,
                 truncate_slug_length=40,
                 version_locations=None,
                 sourceless=False, output_encoding="utf-8"):
        self.dir = dir
        self.file_template = file_template
        self.version_locations = version_locations
        self.truncate_slug_length = truncate_slug_length or 40
        self.sourceless = sourceless
        self.output_encoding = output_encoding
        self.revision_map = revision.RevisionMap(self._load_revisions)

        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 #9
Source File: env.py    From jbox with MIT License 6 votes vote down vote up
def write_script(
        scriptdir, rev_id, content, encoding='ascii', sourceless=False):
    old = scriptdir.revision_map.get_revision(rev_id)
    path = old.path

    content = textwrap.dedent(content)
    if encoding:
        content = content.encode(encoding)
    with open(path, 'wb') as fp:
        fp.write(content)
    pyc_path = util.pyc_file_from_path(path)
    if os.access(pyc_path, os.F_OK):
        os.unlink(pyc_path)
    script = Script._from_path(scriptdir, path)
    old = scriptdir.revision_map.get_revision(script.revision)
    if old.down_revision != script.down_revision:
        raise Exception("Can't change down_revision "
                        "on a refresh operation.")
    scriptdir.revision_map.add_revision(script, _replace=True)

    if sourceless:
        make_sourceless(path) 
Example #10
Source File: cli.py    From ChromaTerm with MIT License 6 votes vote down vote up
def read_file(location):
    """Returns the contents of a file or None on error. The error is printed to
    stderr.

    Args:
        location (str): The location of the file to be read.
    """
    location = os.path.expandvars(location)

    if not os.access(location, os.F_OK):
        eprint('Configuration file', location, 'not found')
        return None

    try:
        with open(location, 'r') as file:
            return file.read()
    except PermissionError:
        eprint('Cannot read configuration file', location, '(permission)')
        return None 
Example #11
Source File: cache.py    From rekall with GNU General Public License v2.0 6 votes vote down vote up
def GetCacheDir(session):
    """Returns the path of a usable cache directory."""
    cache_dir = session.GetParameter("cache_dir")
    if cache_dir == None:
        return cache_dir

    cache_dir = os.path.expandvars(cache_dir)

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

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

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

    return cache_dir 
Example #12
Source File: solvers.py    From MatchingMarkets.py with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def setTmpDir(self):
        """Set the tmpDir attribute to a reasonnable location for a temporary
        directory"""
        if os.name != 'nt':
            # On unix use /tmp by default
            self.tmpDir = os.environ.get("TMPDIR", "/tmp")
            self.tmpDir = os.environ.get("TMP", self.tmpDir)
        else:
            # On Windows use the current directory
            self.tmpDir = os.environ.get("TMPDIR", "")
            self.tmpDir = os.environ.get("TMP", self.tmpDir)
            self.tmpDir = os.environ.get("TEMP", self.tmpDir)
        if not os.path.isdir(self.tmpDir):
            self.tmpDir = ""
        elif not os.access(self.tmpDir, os.F_OK + os.W_OK):
            self.tmpDir = "" 
Example #13
Source File: wheels.py    From oversteer with GNU General Public License v3.0 6 votes vote down vote up
def check_permissions(self, device_id):
        if not os.access(self.devices[device_id]['path'], os.F_OK | os.R_OK | os.X_OK):
            return False
        if not self.check_file_permissions(self.device_file(device_id, 'alternate_modes')):
            return False
        if not self.check_file_permissions(self.device_file(device_id, 'range')):
            return False
        if not self.check_file_permissions(self.device_file(device_id, 'combine_pedals')):
            return False
        if not self.check_file_permissions(self.device_file(device_id, 'gain')):
            return False
        if not self.check_file_permissions(self.device_file(device_id, 'autocenter')):
            return False
        if not self.check_file_permissions(self.device_file(device_id, 'spring_level')):
            return False
        if not self.check_file_permissions(self.device_file(device_id, 'damper_level')):
            return False
        if not self.check_file_permissions(self.device_file(device_id, 'friction_level')):
            return False
        if not self.check_file_permissions(self.device_file(device_id, 'ffb_leds')):
            return False
        if not self.check_file_permissions(self.device_file(device_id, 'peak_ffb_level')):
            return False
        return True 
Example #14
Source File: creation.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def _create_test_db(self, verbosity, autoclobber, keepdb=False):
        test_database_name = self._get_test_db_name()

        if keepdb:
            return test_database_name
        if not self.connection.is_in_memory_db(test_database_name):
            # Erase the old test database
            if verbosity >= 1:
                print("Destroying old test database '%s'..." % self.connection.alias)
            if os.access(test_database_name, os.F_OK):
                if not autoclobber:
                    confirm = input(
                        "Type 'yes' if you would like to try deleting the test "
                        "database '%s', or 'no' to cancel: " % test_database_name
                    )
                if autoclobber or confirm == 'yes':
                    try:
                        os.remove(test_database_name)
                    except Exception as e:
                        sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)
        return test_database_name 
Example #15
Source File: common.py    From pex with Apache License 2.0 6 votes vote down vote up
def can_write_dir(path):
  """Determines if the directory at path can be written to by the current process.

  If the directory doesn't exist, determines if it can be created and thus written to.

  N.B.: This is a best-effort check only that uses permission heuristics and does not actually test
  that the directory can be written to with and writes.

  :param str path: The directory path to test.
  :return: `True` if the given path is a directory that can be written to by the current process.
  :rtype boo:
  """
  while not os.access(path, os.F_OK):
    parent_path = os.path.dirname(path)
    if not parent_path or (parent_path == path):
      # We've recursed up to the root without success, which shouldn't happen,
      return False
    path = parent_path
  return os.path.isdir(path) and os.access(path, os.R_OK | os.W_OK | os.X_OK) 
Example #16
Source File: ez_setup.py    From topical_word_embeddings with 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 #17
Source File: ez_setup.py    From topical_word_embeddings with 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 #18
Source File: ez_setup.py    From topical_word_embeddings with 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 #19
Source File: scp_ICESat2_files.py    From read-ICESat-2 with MIT License 5 votes vote down vote up
def scp_pull_file(client, client_ftp, transfer_file, local_dir, remote_dir,
    CLOBBER=False, VERBOSE=False, LIST=False, MODE=0o775):
    #-- local and remote versions of file
    local_file = os.path.join(local_dir,transfer_file)
    remote_file = posixpath.join(remote_dir,transfer_file)
    #-- check if remote file is newer than the local file
    TEST = False
    OVERWRITE = 'clobber'
    if os.access(local_file, os.F_OK):
        local_mtime = os.stat(local_file).st_mtime
        remote_mtime = client_ftp.stat(remote_file).st_mtime
        #-- if remote file is newer: overwrite the local file
        if (even(remote_mtime) > even(local_mtime)):
            TEST = True
            OVERWRITE = 'overwrite'
    else:
        TEST = True
        OVERWRITE = 'new'
    #-- if file does not exist locally, is to be overwritten, or CLOBBER is set
    if TEST or CLOBBER:
        if VERBOSE or LIST:
            print('{0} --> '.format(remote_file))
            print('\t{0} ({1})\n'.format(local_file,OVERWRITE))
        #-- if not only listing files
        if not LIST:
            #-- copy local files from remote server
            with scp.SCPClient(client.get_transport(), socket_timeout=20) as s:
                s.get(remote_file, local_path=local_file, preserve_times=True)
            #-- change the permissions level of the transported file to MODE
            os.chmod(local_file, MODE)

#-- PURPOSE: rounds a number to an even number less than or equal to original 
Example #20
Source File: test_uuid.py    From oss-ftp with MIT License 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
Source File: bdbag_config.py    From bdbag with Apache License 2.0 5 votes vote down vote up
def bootstrap_config(config_file=DEFAULT_CONFIG_FILE, keychain_file=DEFAULT_KEYCHAIN_FILE, base_dir=None):
    if not base_dir:
        base_dir = os.path.expanduser('~')
    if os.path.isdir(base_dir) and os.access(base_dir, os.F_OK | os.R_OK | os.W_OK | os.X_OK):
        if not os.path.isfile(config_file):
            write_config(config_file=config_file)
            print("Created default configuration file: %s" % config_file)
        else:
            upgrade_config(config_file)
        if not os.path.isfile(keychain_file):
            write_keychain(keychain_file=keychain_file)
            print("Created default keychain file: %s" % keychain_file) 
Example #22
Source File: ez_setup.py    From ec2-cost-tools with 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 #23
Source File: wheels.py    From oversteer with GNU General Public License v3.0 5 votes vote down vote up
def check_file_permissions(self, path):
        if path == None:
            return True
        if not os.access(path, os.F_OK):
            return True
        if os.access(path, os.R_OK | os.W_OK):
            return True
        return False 
Example #24
Source File: _path.py    From Computable with MIT License 5 votes vote down vote up
def access(self, mode):
            """ Return true if current user has access to this path.

            mode - One of the constants os.F_OK, os.R_OK, os.W_OK, os.X_OK
            """
            return os.access(self, mode) 
Example #25
Source File: install.py    From BinderFilter with MIT License 5 votes vote down vote up
def has_msys():
    _msysdll = "msys-1.0.dll"
    for _path in os.environ["PATH"].split(os.pathsep):
        currpath = os.path.join(_path, _msysdll)
        if os.path.isfile(currpath) and os.access(currpath, os.F_OK):
            return _path
    return None 
Example #26
Source File: creation.py    From bioforum with MIT License 5 votes vote down vote up
def _create_test_db(self, verbosity, autoclobber, keepdb=False):
        test_database_name = self._get_test_db_name()

        if keepdb:
            return test_database_name
        if not self.is_in_memory_db(test_database_name):
            # Erase the old test database
            if verbosity >= 1:
                print("Destroying old test database for alias %s..." % (
                    self._get_database_display_str(verbosity, test_database_name),
                ))
            if os.access(test_database_name, os.F_OK):
                if not autoclobber:
                    confirm = input(
                        "Type 'yes' if you would like to try deleting the test "
                        "database '%s', or 'no' to cancel: " % test_database_name
                    )
                if autoclobber or confirm == 'yes':
                    try:
                        os.remove(test_database_name)
                    except Exception as e:
                        sys.stderr.write("Got an error deleting the old test database: %s\n" % e)
                        sys.exit(2)
                else:
                    print("Tests cancelled.")
                    sys.exit(1)
        return test_database_name 
Example #27
Source File: wheels.py    From oversteer with GNU General Public License v3.0 5 votes vote down vote up
def checked_device_file(self, device_id, filename):
        path = self.device_file(device_id, filename)
        if not os.access(path, os.F_OK | os.R_OK | os.W_OK):
            return None
        return path 
Example #28
Source File: configdefaults.py    From D-VAE with MIT License 5 votes vote down vote up
def filter_compiledir(path):
    # Expand '~' in path
    path = os.path.expanduser(path)
    # Turn path into the 'real' path. This ensures that:
    #   1. There is no relative path, which would fail e.g. when trying to
    #      import modules from the compile dir.
    #   2. The path is stable w.r.t. e.g. symlinks (which makes it easier
    #      to re-use compiled modules).
    path = os.path.realpath(path)
    if os.access(path, os.F_OK):  # Do it exist?
        if not os.access(path, os.R_OK | os.W_OK | os.X_OK):
            # If it exist we need read, write and listing access
            raise ValueError(
                "compiledir '%s' exists but you don't have read, write"
                " or listing permissions." % path)
    else:
        try:
            os.makedirs(path, 0o770)  # read-write-execute for user and group
        except OSError as e:
            # Maybe another parallel execution of theano was trying to create
            # the same directory at the same time.
            if e.errno != errno.EEXIST:
                raise ValueError(
                    "Unable to create the compiledir directory"
                    " '%s'. Check the permissions." % path)

    # PROBLEM: sometimes the initial approach based on
    # os.system('touch') returned -1 for an unknown reason; the
    # alternate approach here worked in all cases... it was weird.
    # No error should happen as we checked the permissions.
    init_file = os.path.join(path, '__init__.py')
    if not os.path.exists(init_file):
        try:
            open(init_file, 'w').close()
        except IOError as e:
            if os.path.exists(init_file):
                pass  # has already been created
            else:
                e.args += ('%s exist? %s' % (path, os.path.exists(path)),)
                raise
    return path 
Example #29
Source File: ez_setup.py    From Adafruit_Python_PCA9685 with 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
Source File: FileUtils.py    From CrawlBox with The Unlicense 5 votes vote down vote up
def exists(fileName):
        return os.access(fileName, os.F_OK)