Python stat.S_ISLNK Examples

The following are 30 code examples of stat.S_ISLNK(). 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: list_files.py    From marsnake with GNU General Public License v3.0 6 votes vote down vote up
def list_item(path):
	try:
		_stat = os.lstat(path)

		if path.endswith(os.path.sep):
			path = path.rsplit(os.path.sep, 1)[0]

		name = os.path.basename(path)

		if stat.S_ISLNK(_stat.st_mode):
			try:
				name += ' -> ' + os.readlink(path)
			except:
				pass

		return {
			'name': common.decode2utf8(name),
			'type': file_op.identifytype(path),
			'size': common.size_human_readable(_stat.st_size),
			'ts': time_op.timestamp2string(int(_stat.st_mtime))
		}
	except Exception as e:
		return None 
Example #2
Source File: asserts.py    From testpath with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def assert_islink(path, to=None, msg=None):
    """Assert that path exists and is a symlink.
    
    If to is specified, also check that it is the target of the symlink.
    """
    path = _strpath(path)
    st = _stat_for_assert(path, False, msg)
    if not stat.S_ISLNK(st.st_mode):
        if msg is None:
            msg = "Path exists, but is not a symlink: %r" % path
        raise AssertionError(msg)
    
    if to is not None:
        to = _strpath(to)
        target = os.readlink(path)
        # TODO: Normalise the target to an absolute path?
        if target != to:
            if msg is None:
                msg = _link_target_msg.format(path=path, expected=to, actual=target)
            raise AssertionError(msg) 
Example #3
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 #4
Source File: test_smbclient_os.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_symlink_file_existing_src(smb_share):
    src_filename = "%s\\file.txt" % smb_share
    dst_filename = "%s\\link.txt" % smb_share

    with smbclient.open_file(src_filename, mode='w') as fd:
        fd.write(u"content")

    smbclient.symlink(src_filename, dst_filename)

    actual_files = smbclient.listdir(smb_share)
    assert 'link.txt' in actual_files
    assert 'file.txt' in actual_files

    actual = smbclient.lstat(dst_filename)
    assert stat.S_ISLNK(actual.st_mode)
    assert actual.st_file_attributes == (
        FileAttributes.FILE_ATTRIBUTE_REPARSE_POINT | FileAttributes.FILE_ATTRIBUTE_ARCHIVE) 
Example #5
Source File: fastdupes.py    From fastdupes with GNU General Public License v2.0 6 votes vote down vote up
def sizeClassifier(path, min_size=DEFAULTS['min_size']):
    """Sort a file into a group based on on-disk size.

    :param paths: See :func:`fastdupes.groupify`

    :param min_size: Files smaller than this size (in bytes) will be ignored.
    :type min_size: :class:`__builtins__.int`

    :returns: See :func:`fastdupes.groupify`

    .. todo:: Rework the calling of :func:`~os.stat` to minimize the number of
        calls. It's a fairly significant percentage of the time taken according
        to the profiler.
    """
    filestat = _stat(path)
    if stat.S_ISLNK(filestat.st_mode):
        return  # Skip symlinks.

    if filestat.st_size < min_size:
        return  # Skip files below the size limit

    return filestat.st_size 
Example #6
Source File: test_smbclient_os.py    From smbprotocol with MIT License 6 votes vote down vote up
def test_symlink_relative_src(smb_share):
    src_filename = "%s\\dir1\\file.txt" % smb_share
    dst_filename = "%s\\dir2\\link.txt" % smb_share

    smbclient.mkdir("%s\\dir1" % smb_share)
    smbclient.mkdir("%s\\dir2" % smb_share)

    with smbclient.open_file(src_filename, mode='w') as fd:
        fd.write(u"content")

    smbclient.symlink("..\\dir1\\file.txt", dst_filename)

    with smbclient.open_file(dst_filename) as fd:
        assert fd.read() == u"content"

    actual = smbclient.lstat(dst_filename)
    assert stat.S_ISLNK(actual.st_mode)
    assert actual.st_file_attributes == (
        FileAttributes.FILE_ATTRIBUTE_REPARSE_POINT | FileAttributes.FILE_ATTRIBUTE_ARCHIVE) 
Example #7
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 #8
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 #9
Source File: FileConditions.py    From llvm-zorg with Apache License 2.0 6 votes vote down vote up
def __call__(self, step):
        slavever = step.slaveVersion('stat')
        if not slavever:
            raise BuildSlaveTooOldError("slave is too old, does not know "
                                        "about stat")

        def commandComplete(cmd):
            if cmd.rc != 0:
                return False

            s = cmd.updates["stat"][-1]
            filemode = s[stat.ST_MODE]
            if stat.S_ISREG(filemode) or stat.S_ISLNK(filemode):
                # True only if this is a file or a link and not any other file
                # system object.
                return True
            else:
                return False

        cmd = LoggedRemoteCommand('stat', {'file': self.filename})
        d = step.runCommand(cmd)
        d.addCallback(lambda res: commandComplete(cmd))
        return d 
Example #10
Source File: manifest.py    From Mastering-Elasticsearch-7.0 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 #11
Source File: FS.py    From pivy with ISC License 5 votes vote down vote up
def islink(self):
            try: st = self.fs.lstat(self.abspath)
            except os.error: return 0
            return stat.S_ISLNK(st[stat.ST_MODE]) 
Example #12
Source File: manifest.py    From anpr with Creative Commons Attribution 4.0 International 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 #13
Source File: manifest.py    From Safejumper-for-Desktop with GNU General Public License v2.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 #14
Source File: device_utils_test.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testStatDirectory_fileModes(self):
    expected_modes = (
      ('some_dir', stat.S_ISDIR),
      ('some_file', stat.S_ISREG),
      ('lnk', stat.S_ISLNK),
      ('a_socket1', stat.S_ISSOCK),
      ('block_dev', stat.S_ISBLK),
      ('random', stat.S_ISCHR),
    )
    entries = self.getStatEntries()
    for filename, check in expected_modes:
      self.assertTrue(check(entries[filename]['st_mode'])) 
Example #15
Source File: posixpath.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def islink(path):
    """Test whether a path is a symbolic link"""
    try:
        st = os.lstat(path)
    except (OSError, AttributeError):
        return False
    return stat.S_ISLNK(st.st_mode)

# Being true for dangling symbolic links is also useful. 
Example #16
Source File: posixpath.py    From GraphicDesignPatternByPython with MIT License 5 votes vote down vote up
def ismount(path):
    """Test whether a path is a mount point"""
    try:
        s1 = os.lstat(path)
    except OSError:
        # It doesn't exist -- so not a mount point. :-)
        return False
    else:
        # A symlink can never be a mount point
        if stat.S_ISLNK(s1.st_mode):
            return False

    if isinstance(path, bytes):
        parent = join(path, b'..')
    else:
        parent = join(path, '..')
    parent = realpath(parent)
    try:
        s2 = os.lstat(parent)
    except OSError:
        return False

    dev1 = s1.st_dev
    dev2 = s2.st_dev
    if dev1 != dev2:
        return True     # path/.. on a different device as path
    ino1 = s1.st_ino
    ino2 = s2.st_ino
    if ino1 == ino2:
        return True     # path/.. is the same i-node as path
    return False


# 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 #17
Source File: device_utils_test.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testStatDirectory_fileModes(self):
    expected_modes = (
      ('some_dir', stat.S_ISDIR),
      ('some_file', stat.S_ISREG),
      ('lnk', stat.S_ISLNK),
      ('a_socket1', stat.S_ISSOCK),
      ('block_dev', stat.S_ISBLK),
      ('random', stat.S_ISCHR),
    )
    entries = self.getStatEntries()
    for filename, check in expected_modes:
      self.assertTrue(check(entries[filename]['st_mode'])) 
Example #18
Source File: device_utils_test.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testStatDirectory_symbolicLinks(self):
    entries = self.getStatEntries()
    self.assertEqual(entries['lnk']['symbolic_link_to'], '/some/path')
    for d in entries.itervalues():
      self.assertEqual('symbolic_link_to' in d, stat.S_ISLNK(d['st_mode'])) 
Example #19
Source File: device_utils_test.py    From Jandroid with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def testStatDirectory_fileModes(self):
    expected_modes = (
      ('some_dir', stat.S_ISDIR),
      ('some_file', stat.S_ISREG),
      ('lnk', stat.S_ISLNK),
      ('a_socket1', stat.S_ISSOCK),
      ('block_dev', stat.S_ISBLK),
      ('random', stat.S_ISCHR),
    )
    entries = self.getStatEntries()
    for filename, check in expected_modes:
      self.assertTrue(check(entries[filename]['st_mode'])) 
Example #20
Source File: manifest.py    From Mastering-Elasticsearch-7.0 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 #21
Source File: manifest.py    From deepWordBug 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 #22
Source File: posixpath.py    From oss-ftp with MIT License 5 votes vote down vote up
def islink(path):
    """Test whether a path is a symbolic link"""
    try:
        st = os.lstat(path)
    except (os.error, AttributeError):
        return False
    return stat.S_ISLNK(st.st_mode)

# Being true for dangling symbolic links is also useful. 
Example #23
Source File: filelist.py    From oss-ftp 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 #24
Source File: manifest.py    From oss-ftp 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 #25
Source File: filelist.py    From Computable 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 #26
Source File: posixpath.py    From BinderFilter with MIT License 5 votes vote down vote up
def islink(path):
    """Test whether a path is a symbolic link"""
    try:
        st = os.lstat(path)
    except (os.error, AttributeError):
        return False
    return stat.S_ISLNK(st.st_mode)

# Being true for dangling symbolic links is also useful. 
Example #27
Source File: filelist.py    From BinderFilter 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 #28
Source File: asserts.py    From testpath with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def assert_not_islink(path, msg=None):
    """Assert that path exists but is not a symlink.
    """
    path = _strpath(path)
    st = _stat_for_assert(path, False, msg)
    if stat.S_ISLNK(st.st_mode):
        if msg is None:
            msg = "Path is a symlink: %r" % path
        raise AssertionError(msg) 
Example #29
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 #30
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)