Python stat.S_ISDIR Examples

The following are 30 code examples of stat.S_ISDIR(). 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 stat , or try the search function .
Example #1
Source File: __init__.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def _rmtree(path):
        try:
            shutil.rmtree(path)
            return
        except EnvironmentError:
            pass

        def _rmtree_inner(path):
            for name in _force_run(path, os.listdir, path):
                fullname = os.path.join(path, name)
                try:
                    mode = os.lstat(fullname).st_mode
                except EnvironmentError:
                    mode = 0
                if stat.S_ISDIR(mode):
                    _rmtree_inner(fullname)
                    _force_run(path, os.rmdir, fullname)
                else:
                    _force_run(path, os.unlink, fullname)
        _rmtree_inner(path)
        os.rmdir(path) 
Example #2
Source File: _os.py    From smbprotocol with MIT License 6 votes vote down vote up
def is_dir(self, follow_symlinks=True):
        """
        Return 'True' if this entry is a directory or a symbolic link pointing to a directory; return 'False' if the
        entry is or points to any other kind of file, or if it doesn't exist anymore.

        If follow_symlinks is 'False', return 'True' only if this entry is a directory (without following symlinks);
        return 'False' if the entry is any other kind of file.

        The result is cached on the 'smcblient.DirEntry' object, with a separate cache for follow_symlinks 'True' and
        'False'. Call 'smbclient.path.isdir(entry.path)' to fetch up-to-date information.

        On the first, uncached call, no SMB call is required unless the path is a reparse point.

        :param follow_symlinks: Whether to check if the entry's target is a directory (True) or the entry itself
            (False) if the entry is a symlink.
        :return: bool that states whether the entry is a directory or not.
        """
        is_lnk = self.is_symlink()
        if follow_symlinks and is_lnk:
            return self._link_target_type_check(py_stat.S_ISDIR)
        else:
            # Python behaviour is to consider a symlink not a directory even if it has the DIRECTORY attribute.
            return not is_lnk and self._dir_info['file_attributes'].has_flag(FileAttributes.FILE_ATTRIBUTE_DIRECTORY) 
Example #3
Source File: utils.py    From bob with GNU General Public License v3.0 6 votes vote down vote up
def __hashEntry(self, prefix, entry, s):
        if stat.S_ISREG(s.st_mode):
            digest = self.__index.check(prefix, entry, s, hashFile)
        elif stat.S_ISDIR(s.st_mode):
            digest = self.__hashDir(prefix, entry)
        elif stat.S_ISLNK(s.st_mode):
            digest = self.__index.check(prefix, entry, s, DirHasher.__hashLink)
        elif stat.S_ISBLK(s.st_mode) or stat.S_ISCHR(s.st_mode):
            digest = struct.pack("<L", s.st_rdev)
        elif stat.S_ISFIFO(s.st_mode):
            digest = b''
        else:
            digest = b''
            logging.getLogger(__name__).warning("Unknown file: %s", entry)

        return digest 
Example #4
Source File: sftp.py    From filesystem_spec with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def info(self, path):
        s = self.ftp.stat(path)
        if S_ISDIR(s.st_mode):
            t = "directory"
        elif S_ISLNK(s.st_mode):
            t = "link"
        else:
            t = "file"
        return {
            "name": path + "/" if t == "directory" else path,
            "size": s.st_size,
            "type": t,
            "uid": s.st_uid,
            "gid": s.st_gid,
            "time": s.st_atime,
            "mtime": s.st_mtime,
        } 
Example #5
Source File: plugin.py    From phpsploit with GNU General Public License v3.0 6 votes vote down vote up
def mode_filetype(mode):
    mode = stat.S_IFMT(mode)
    dic = {
            stat.S_ISFIFO: "fifo file",
            stat.S_ISCHR: "character device",
            stat.S_ISDIR: "directory",
            stat.S_ISBLK: "block device",
            stat.S_ISREG: "regular file",
            stat.S_ISLNK: "symbolic link",
            stat.S_ISSOCK: "socket",
            stat.S_ISDOOR: "door",
            }
    for test_func, name in dic.items():
        if test_func(mode):
            return name
    return "???" 
Example #6
Source File: common.py    From deplicate with MIT License 5 votes vote down vote up
def splitpaths(iterable, followlinks=False):
    dirs = []
    files = []
    links = []
    nodes = []
    unexs = []

    for path in iterable:
        try:
            mode, symlink = _stat(path)

        except OSError:
            unexs.append(path)

        else:
            if S_ISDIR(mode):
                if symlink and not followlinks:
                    continue
                dirs.append(path)

            elif S_ISREG(mode):
                (links if symlink else files).append(path)

            else:
                nodes.append(path)

    return dirs, files, links, nodes, unexs 
Example #7
Source File: FS.py    From web2board with GNU Lesser General Public License v3.0 5 votes vote down vote up
def isdir(self):
        st = self.stat()
        return st is not None and stat.S_ISDIR(st[stat.ST_MODE]) 
Example #8
Source File: asserts.py    From testpath with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def assert_not_isdir(path, follow_symlinks=True, msg=None):
    """Assert that path exists but is not a directory.
    
    With follow_symlinks=True, the default, this will fail if path is a symlink
    to a directory. With follow_symlinks=False, it will pass in that case.
    """
    path = _strpath(path)
    st = _stat_for_assert(path, follow_symlinks, msg)
    if stat.S_ISDIR(st.st_mode):
        if msg is None:
            msg = "Path is a directory: %r" % path
        raise AssertionError(msg) 
Example #9
Source File: asserts.py    From testpath with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def assert_isdir(path, follow_symlinks=True, msg=None):
    """Assert that path exists and is a directory.
    
    With follow_symlinks=True, the default, this will pass if path is a symlink
    to a directory. With follow_symlinks=False, it will fail in that case.
    """
    path = _strpath(path)
    st = _stat_for_assert(path, follow_symlinks, msg)
    if not stat.S_ISDIR(st.st_mode):
        if msg is None:
            msg = "Path exists, but is not a directory: %r" % path
        raise AssertionError(msg) 
Example #10
Source File: manifest.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def findall(self):
        """Find all files under the base and set ``allfiles`` to the absolute
        pathnames of files found.
        """
        from stat import S_ISREG, S_ISDIR, S_ISLNK

        self.allfiles = allfiles = []
        root = self.base
        stack = [root]
        pop = stack.pop
        push = stack.append

        while stack:
            root = pop()
            names = os.listdir(root)

            for name in names:
                fullname = os.path.join(root, name)

                # Avoid excess stat calls -- just one will do, thank you!
                stat = os.stat(fullname)
                mode = stat.st_mode
                if S_ISREG(mode):
                    allfiles.append(fsdecode(fullname))
                elif S_ISDIR(mode) and not S_ISLNK(mode):
                    push(fullname) 
Example #11
Source File: manifest.py    From FuYiSpider with Apache License 2.0 5 votes vote down vote up
def findall(self):
        """Find all files under the base and set ``allfiles`` to the absolute
        pathnames of files found.
        """
        from stat import S_ISREG, S_ISDIR, S_ISLNK

        self.allfiles = allfiles = []
        root = self.base
        stack = [root]
        pop = stack.pop
        push = stack.append

        while stack:
            root = pop()
            names = os.listdir(root)

            for name in names:
                fullname = os.path.join(root, name)

                # Avoid excess stat calls -- just one will do, thank you!
                stat = os.stat(fullname)
                mode = stat.st_mode
                if S_ISREG(mode):
                    allfiles.append(fsdecode(fullname))
                elif S_ISDIR(mode) and not S_ISLNK(mode):
                    push(fullname) 
Example #12
Source File: genericpath.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def isdir(s):
    """Return true if the pathname refers to an existing directory."""
    try:
        st = os.stat(s)
    except os.error:
        return False
    return stat.S_ISDIR(st.st_mode) 
Example #13
Source File: test_contracts.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def cwd(self, ret, proc):
        if ret:     # 'ret' can be None or empty
            self.assertIsInstance(ret, str)
            assert os.path.isabs(ret), ret
            try:
                st = os.stat(ret)
            except OSError as err:
                if WINDOWS and err.errno in \
                        psutil._psplatform.ACCESS_DENIED_SET:
                    pass
                # directory has been removed in mean time
                elif err.errno != errno.ENOENT:
                    raise
            else:
                assert stat.S_ISDIR(st.st_mode) 
Example #14
Source File: __init__.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def safe_rmpath(path):
    "Convenience function for removing temporary test files or dirs"
    def retry_fun(fun):
        # On Windows it could happen that the file or directory has
        # open handles or references preventing the delete operation
        # to succeed immediately, so we retry for a while. See:
        # https://bugs.python.org/issue33240
        stop_at = time.time() + 1
        while time.time() < stop_at:
            try:
                return fun()
            except WindowsError as _:
                err = _
                if err.errno != errno.ENOENT:
                    raise
                else:
                    warn("ignoring %s" % (str(err)))
                    time.sleep(0.01)
        raise err

    try:
        st = os.stat(path)
        if stat.S_ISDIR(st.st_mode):
            fun = functools.partial(shutil.rmtree, path)
        else:
            fun = functools.partial(os.remove, path)
        if POSIX:
            fun()
        else:
            retry_fun(fun)
    except OSError as err:
        if err.errno != errno.ENOENT:
            raise 
Example #15
Source File: manifest.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def findall(self):
        """Find all files under the base and set ``allfiles`` to the absolute
        pathnames of files found.
        """
        from stat import S_ISREG, S_ISDIR, S_ISLNK

        self.allfiles = allfiles = []
        root = self.base
        stack = [root]
        pop = stack.pop
        push = stack.append

        while stack:
            root = pop()
            names = os.listdir(root)

            for name in names:
                fullname = os.path.join(root, name)

                # Avoid excess stat calls -- just one will do, thank you!
                stat = os.stat(fullname)
                mode = stat.st_mode
                if S_ISREG(mode):
                    allfiles.append(fsdecode(fullname))
                elif S_ISDIR(mode) and not S_ISLNK(mode):
                    push(fullname) 
Example #16
Source File: manifest.py    From Python24 with MIT License 5 votes vote down vote up
def findall(self):
        """Find all files under the base and set ``allfiles`` to the absolute
        pathnames of files found.
        """
        from stat import S_ISREG, S_ISDIR, S_ISLNK

        self.allfiles = allfiles = []
        root = self.base
        stack = [root]
        pop = stack.pop
        push = stack.append

        while stack:
            root = pop()
            names = os.listdir(root)

            for name in names:
                fullname = os.path.join(root, name)

                # Avoid excess stat calls -- just one will do, thank you!
                stat = os.stat(fullname)
                mode = stat.st_mode
                if S_ISREG(mode):
                    allfiles.append(fsdecode(fullname))
                elif S_ISDIR(mode) and not S_ISLNK(mode):
                    push(fullname) 
Example #17
Source File: tempfile.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _rmtree_unsafe(path, onerror):
    try:
        if _os.path.islink(path):
            # symlinks to directories are forbidden, see bug #1669
            raise OSError("Cannot call rmtree on a symbolic link")
    except OSError:
        onerror(_os.path.islink, path, _sys.exc_info())
        # can't continue even if onerror hook returns
        return
    names = []
    try:
        names = _os.listdir(path)
    except OSError:
        onerror(_os.listdir, path, _sys.exc_info())
    for name in names:
        fullname = _os.path.join(path, name)
        try:
            mode = _os.lstat(fullname).st_mode
        except OSError:
            mode = 0
        if _stat.S_ISDIR(mode):
            _rmtree_unsafe(fullname, onerror)
        else:
            try:
                _os.unlink(fullname)
            except OSError:
                onerror(_os.unlink, fullname, _sys.exc_info())
    try:
        _os.rmdir(path)
    except OSError:
        onerror(_os.rmdir, path, _sys.exc_info())

  # Version using fd-based APIs to protect against races 
Example #18
Source File: shutil.py    From kobo-predict with BSD 2-Clause "Simplified" License 5 votes vote down vote up
def _rmtree_unsafe(path, onerror):
    try:
        if os.path.islink(path):
            # symlinks to directories are forbidden, see bug #1669
            raise OSError("Cannot call rmtree on a symbolic link")
    except OSError:
        onerror(os.path.islink, path, sys.exc_info())
        # can't continue even if onerror hook returns
        return
    names = []
    try:
        names = os.listdir(path)
    except OSError:
        onerror(os.listdir, path, sys.exc_info())
    for name in names:
        fullname = os.path.join(path, name)
        try:
            mode = os.lstat(fullname).st_mode
        except OSError:
            mode = 0
        if stat.S_ISDIR(mode):
            _rmtree_unsafe(fullname, onerror)
        else:
            try:
                os.unlink(fullname)
            except OSError:
                onerror(os.unlink, fullname, sys.exc_info())
    try:
        os.rmdir(path)
    except OSError:
        onerror(os.rmdir, path, sys.exc_info())

# Version using fd-based APIs to protect against races 
Example #19
Source File: easy_install.py    From lambda-chef-node-cleanup with Apache License 2.0 5 votes vote down vote up
def rmtree(path, ignore_errors=False, onerror=auto_chmod):
    """Recursively delete a directory tree.

    This code is taken from the Python 2.4 version of 'shutil', because
    the 2.3 version doesn't really work right.
    """
    if ignore_errors:
        def onerror(*args):
            pass
    elif onerror is None:
        def onerror(*args):
            raise
    names = []
    try:
        names = os.listdir(path)
    except os.error:
        onerror(os.listdir, path, sys.exc_info())
    for name in names:
        fullname = os.path.join(path, name)
        try:
            mode = os.lstat(fullname).st_mode
        except os.error:
            mode = 0
        if stat.S_ISDIR(mode):
            rmtree(fullname, ignore_errors, onerror)
        else:
            try:
                os.remove(fullname)
            except os.error:
                onerror(os.remove, fullname, sys.exc_info())
    try:
        os.rmdir(path)
    except os.error:
        onerror(os.rmdir, path, sys.exc_info()) 
Example #20
Source File: posixpath.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def walk(top, func, arg):
    """Directory tree walk with callback function.

    For each directory in the directory tree rooted at top (including top
    itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
    dirname is the name of the directory, and fnames a list of the names of
    the files and subdirectories in dirname (excluding '.' and '..').  func
    may modify the fnames list in-place (e.g. via del or slice assignment),
    and walk will only recurse into the subdirectories whose names remain in
    fnames; this can be used to implement a filter, or to impose a specific
    order of visiting.  No semantics are defined for, or required of, arg,
    beyond that arg is always passed to func.  It can be used, e.g., to pass
    a filename pattern, or a mutable object designed to accumulate
    statistics.  Passing None for arg is common."""
    warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.",
                      stacklevel=2)
    try:
        names = os.listdir(top)
    except os.error:
        return
    func(arg, top, names)
    for name in names:
        name = join(top, name)
        try:
            st = os.lstat(name)
        except os.error:
            continue
        if stat.S_ISDIR(st.st_mode):
            walk(name, func, arg)


# Expand paths beginning with '~' or '~user'.
# '~' means $HOME; '~user' means that user's home directory.
# If the path doesn't begin with '~', or if the user or $HOME is unknown,
# the path is returned unchanged (leaving error reporting to whatever
# function is called with the expanded path as argument).
# See also module 'glob' for expansion of *, ? and [...] in pathnames.
# (A function should also be defined to do full *sh-style environment
# variable expansion.) 
Example #21
Source File: dataset_integrity.py    From DeepDIVA with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _process_folder(path):
    """
    Recursively descend the directory tree rooted at path,
    calling _process_file() function for each regular file

    Parameters
    ----------
    path : String (path)
        Path to folder to navigate

    Returns
    -------
        A dictionary of the format explained in generate_integrity_footprint() above.
    """
    logging.debug("Exploring folder: {}".format(path))

    # Init the dictionary to host the data
    data = {}
    data['files'] = []
    data['folders'] = []
    data['path'] = path

    # Iterate in all files into the folder
    for f in os.scandir(path=path):
        # Need to skip the footprint.json
        if f.name == 'footprint.json':
            continue
        pathname = os.path.join(path, f.name)
        mode = os.stat(pathname).st_mode
        if S_ISDIR(mode):
            # It's a directory, recurse into it
            data['folders'].append(_process_folder(pathname))
        elif S_ISREG(mode):
            # It's a file, hash it
            data['files'].append(_process_file(pathname))
        else:
            # Unknown file type, print a message
            print('Unknown  file type, skipping %s' % pathname)
    return data 
Example #22
Source File: test_mailbox.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def _check_basics(self, factory=None):
        # (Used by test_open_new() and test_open_existing().)
        self.assertEqual(self._box._path, os.path.abspath(self._path))
        self.assertEqual(self._box._factory, factory)
        for subdir in '', 'tmp', 'new', 'cur':
            path = os.path.join(self._path, subdir)
            mode = os.stat(path)[stat.ST_MODE]
            self.assertTrue(stat.S_ISDIR(mode), "Not a directory: '%s'" % path) 
Example #23
Source File: filelist.py    From ironpython2 with Apache License 2.0 5 votes vote down vote up
def findall(dir = os.curdir):
    """Find all files under 'dir' and return the list of full filenames
    (relative to 'dir').
    """
    from stat import ST_MODE, S_ISREG, S_ISDIR, S_ISLNK

    list = []
    stack = [dir]
    pop = stack.pop
    push = stack.append

    while stack:
        dir = pop()
        names = os.listdir(dir)

        for name in names:
            if dir != os.curdir:        # avoid the dreaded "./" syndrome
                fullname = os.path.join(dir, name)
            else:
                fullname = name

            # Avoid excess stat calls -- just one will do, thank you!
            stat = os.stat(fullname)
            mode = stat[ST_MODE]
            if S_ISREG(mode):
                list.append(fullname)
            elif S_ISDIR(mode) and not S_ISLNK(mode):
                push(fullname)

    return list 
Example #24
Source File: utils.py    From bob with GNU General Public License v3.0 5 votes vote down vote up
def __hashDir(self, prefix, path=b''):
        entries = []
        try:
            dirEntries = os.listdir(os.path.join(prefix, path if path else b'.'))
        except OSError as e:
            logging.getLogger(__name__).warning("Cannot list directory: %s", str(e))
            dirEntries = []

        for f in dirEntries:
            e = os.path.join(path, f)
            try:
                s = os.lstat(os.path.join(prefix, e))
                if stat.S_ISDIR(s.st_mode):
                    # skip useless directories
                    if f in self.__ignoreDirs: continue
                    # add training '/' for directores for correct sorting
                    f = f + os.fsencode(os.path.sep)
                else:
                    # skip useless files
                    if f in DirHasher.IGNORE_FILES: continue
                entries.append((e, f, s))
            except OSError as err:
                logging.getLogger(__name__).warning("Cannot stat '%s': %s", e, str(err))
        entries = sorted(entries, key=lambda x: x[1])
        dirList = [
            (struct.pack("=L", s.st_mode) + self.__hashEntry(prefix, e, s) + f)
            for (e, f, s) in entries
        ]
        dirBlob = b"".join(dirList)
        m = hashlib.sha1()
        m.update(dirBlob)
        return m.digest() 
Example #25
Source File: wheel.py    From poetry with MIT License 5 votes vote down vote up
def _add_file(self, wheel, full_path, rel_path):
        full_path, rel_path = str(full_path), str(rel_path)
        if os.sep != "/":
            # We always want to have /-separated paths in the zip file and in
            # RECORD
            rel_path = rel_path.replace(os.sep, "/")

        zinfo = zipfile.ZipInfo(rel_path)

        # Normalize permission bits to either 755 (executable) or 644
        st_mode = os.stat(full_path).st_mode
        new_mode = normalize_file_permissions(st_mode)
        zinfo.external_attr = (new_mode & 0xFFFF) << 16  # Unix attributes

        if stat.S_ISDIR(st_mode):
            zinfo.external_attr |= 0x10  # MS-DOS directory flag

        hashsum = hashlib.sha256()
        with open(full_path, "rb") as src:
            while True:
                buf = src.read(1024 * 8)
                if not buf:
                    break
                hashsum.update(buf)

            src.seek(0)
            wheel.writestr(zinfo, src.read(), compress_type=zipfile.ZIP_DEFLATED)

        size = os.stat(full_path).st_size
        hash_digest = urlsafe_b64encode(hashsum.digest()).decode("ascii").rstrip("=")

        self._records.append((rel_path, hash_digest, size)) 
Example #26
Source File: FS.py    From arnold-usd with Apache License 2.0 5 votes vote down vote up
def isdir(self):
        st = self.stat()
        return st is not None and stat.S_ISDIR(st[stat.ST_MODE]) 
Example #27
Source File: posixpath.py    From meddle with MIT License 5 votes vote down vote up
def walk(top, func, arg):
    """Directory tree walk with callback function.

    For each directory in the directory tree rooted at top (including top
    itself, but excluding '.' and '..'), call func(arg, dirname, fnames).
    dirname is the name of the directory, and fnames a list of the names of
    the files and subdirectories in dirname (excluding '.' and '..').  func
    may modify the fnames list in-place (e.g. via del or slice assignment),
    and walk will only recurse into the subdirectories whose names remain in
    fnames; this can be used to implement a filter, or to impose a specific
    order of visiting.  No semantics are defined for, or required of, arg,
    beyond that arg is always passed to func.  It can be used, e.g., to pass
    a filename pattern, or a mutable object designed to accumulate
    statistics.  Passing None for arg is common."""
    warnings.warnpy3k("In 3.x, os.path.walk is removed in favor of os.walk.",
                      stacklevel=2)
    try:
        names = os.listdir(top)
    except os.error:
        return
    func(arg, top, names)
    for name in names:
        name = join(top, name)
        try:
            st = os.lstat(name)
        except os.error:
            continue
        if stat.S_ISDIR(st.st_mode):
            walk(name, func, arg)


# Expand paths beginning with '~' or '~user'.
# '~' means $HOME; '~user' means that user's home directory.
# If the path doesn't begin with '~', or if the user or $HOME is unknown,
# the path is returned unchanged (leaving error reporting to whatever
# function is called with the expanded path as argument).
# See also module 'glob' for expansion of *, ? and [...] in pathnames.
# (A function should also be defined to do full *sh-style environment
# variable expansion.) 
Example #28
Source File: genericpath.py    From meddle with MIT License 5 votes vote down vote up
def isdir(s):
    """Return true if the pathname refers to an existing directory."""
    try:
        st = os.stat(s)
    except os.error:
        return False
    return stat.S_ISDIR(st.st_mode) 
Example #29
Source File: filelist.py    From meddle with MIT License 5 votes vote down vote up
def findall(dir = os.curdir):
    """Find all files under 'dir' and return the list of full filenames
    (relative to 'dir').
    """
    from stat import ST_MODE, S_ISREG, S_ISDIR, S_ISLNK

    list = []
    stack = [dir]
    pop = stack.pop
    push = stack.append

    while stack:
        dir = pop()
        names = os.listdir(dir)

        for name in names:
            if dir != os.curdir:        # avoid the dreaded "./" syndrome
                fullname = os.path.join(dir, name)
            else:
                fullname = name

            # Avoid excess stat calls -- just one will do, thank you!
            stat = os.stat(fullname)
            mode = stat[ST_MODE]
            if S_ISREG(mode):
                list.append(fullname)
            elif S_ISDIR(mode) and not S_ISLNK(mode):
                push(fullname)

    return list 
Example #30
Source File: local.py    From python-netsurv with MIT License 5 votes vote down vote up
def dir(self):
            return S_ISDIR(self._stat().mode)