我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用os.lstat()。
def lexists(path): """Test whether a path exists. Returns True for broken symbolic links""" try: st = os.lstat(path) except OSError: return False return True # Is a path a mount point? # Any drive letter root (eg c:\) # Any share UNC (eg \\server\share) # Any volume mounted on a filesystem folder # # No one method detects all three situations. Historically we've lexically # detected drive letter roots and share UNCs. The canonical approach to # detecting mounted volumes (querying the reparse tag) fails for the most # common case: drive letter roots. The alternative which uses GetVolumePathName # fails if the drive letter is the result of a SUBST.
def copymode(src, dst, *, follow_symlinks=True): """Copy mode bits from src to dst. If follow_symlinks is not set, symlinks aren't followed if and only if both `src` and `dst` are symlinks. If `lchmod` isn't available (e.g. Linux) this method does nothing. """ if not follow_symlinks and os.path.islink(src) and os.path.islink(dst): if hasattr(os, 'lchmod'): stat_func, chmod_func = os.lstat, os.lchmod else: return elif hasattr(os, 'chmod'): stat_func, chmod_func = os.stat, os.chmod else: return st = stat_func(src) chmod_func(dst, stat.S_IMODE(st.st_mode))
def copytree(src, dst, symlinks = False, ignore = None): if not os.path.exists(dst): os.makedirs(dst) shutil.copystat(src, dst) lst = os.listdir(src) if ignore: excl = ignore(src, lst) lst = [x for x in lst if x not in excl] for item in lst: s = os.path.join(src, item) d = os.path.join(dst, item) if symlinks and os.path.islink(s): if os.path.lexists(d): os.remove(d) os.symlink(os.readlink(s), d) try: st = os.lstat(s) mode = stat.S_IMODE(st.st_mode) os.lchmod(d, mode) except: pass # lchmod not available elif os.path.isdir(s): copytree(s, d, symlinks, ignore) else: shutil.copy2(s, d)
def is_partition(self, dev): """ Check whether a given device path is a partition or a full disk. """ if not os.path.exists(dev): raise Error('device not found', dev) dev = os.path.realpath(dev) if not stat.S_ISBLK(os.lstat(dev).st_mode): raise Error('not a block device', dev) name = self._get_dev_name(dev) if os.path.exists(os.path.join('/sys/block', name)): return False # make sure it is a partition of something else for basename in os.listdir('/sys/block'): if os.path.exists(os.path.join('/sys/block', basename, name)): return True raise Error('not a disk or partition', dev)
def getattr(self, path, fh=None): full_path = self.join_path(path) st = os.lstat(full_path) attr = dict((key, getattr(st, key)) for key in ( 'st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid' ) ) return attr
def getattr(self, path, fh=None): full_path = self._full_path(path) st = os.lstat(full_path) attr = dict((key, getattr(st, key)) for key in ( 'st_atime', 'st_ctime', 'st_gid', 'st_mode', 'st_mtime', 'st_nlink', 'st_size', 'st_uid' ) ) return attr
def find_ext_volume_global_trash(volume_root): # from [2] Trash directories (1) check for a .Trash dir with the right # permissions set. trash_dir = op.join(volume_root, TOPDIR_TRASH) if not op.exists(trash_dir): return None mode = os.lstat(trash_dir).st_mode # vol/.Trash must be a directory, cannot be a symlink, and must have the # sticky bit set. if not op.isdir(trash_dir) or op.islink(trash_dir) or not (mode & stat.S_ISVTX): return None trash_dir = op.join(trash_dir, str(uid)) try: check_create(trash_dir) except OSError: return None return trash_dir
def stat(self, follow_symlinks=True): if follow_symlinks: if self._stat is None: if self.is_symlink(): # It's a symlink, call link-following stat() self._stat = stat(self.path) else: # Not a symlink, stat is same as lstat value if self._lstat is None: self._lstat = find_data_to_stat(self._find_data) self._stat = self._lstat return self._stat else: if self._lstat is None: # Lazily convert to stat object, because it's slow # in Python, and often we only need is_dir() etc self._lstat = find_data_to_stat(self._find_data) return self._lstat
def map_id(path, map_uid, map_gid): """ Remapping ownership of all files inside a container's rootfs. map_gid and map_uid: Contain integers in a list with format: [<start>, <target>, <count>] """ if map_uid: uid_opts = get_mapping_opts(map_uid) if map_gid: gid_opts = get_mapping_opts(map_gid) for root, _ignore, files in os.walk(os.path.realpath(path)): for name in [root] + files: file_path = os.path.join(root, name) stat_info = os.lstat(file_path) old_uid = stat_info.st_uid old_gid = stat_info.st_gid new_uid = get_map_id(old_uid, uid_opts) if map_uid else -1 new_gid = get_map_id(old_gid, gid_opts) if map_gid else -1 os.lchown(file_path, new_uid, new_gid)
def dirname(p): """Returns the directory component of a pathname""" return split(p)[0] # Is a path a symbolic link? # This will always return false on systems where os.lstat doesn't exist.
def islink(path): """Test whether a path is a symbolic link. This will always return false for Windows prior to 6.0. """ 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.
def dirname(p): """Returns the directory component of a pathname""" p = os.fspath(p) sep = _get_sep(p) i = p.rfind(sep) + 1 head = p[:i] if head and head != sep*len(head): head = head.rstrip(sep) return head # Is a path a symbolic link? # This will always return false on systems where os.lstat doesn't exist.
def lexists(path): """Test whether a path exists. Returns True for broken symbolic links""" try: os.lstat(path) except OSError: return False return True # Is a path a mount point? # (Does this work for all UNIXes? Is it even guaranteed to work by Posix?)
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.)
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
def dirname(p): """Returns the directory component of a pathname""" i = p.rfind('/') + 1 head = p[:i] if head and head != '/'*len(head): head = head.rstrip('/') return head # Is a path a symbolic link? # This will always return false on systems where os.lstat doesn't exist.
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.
def lexists(path): """Test whether a path exists. Returns True for broken symbolic links""" try: os.lstat(path) except os.error: return False return True # Are two filenames really pointing to the same file?
def sameopenfile(fp1, fp2): """Test whether two open file objects reference the same file""" s1 = os.fstat(fp1) s2 = os.fstat(fp2) return samestat(s1, s2) # Are two stat buffers (obtained from stat, fstat or lstat) # describing the same file?
def ismount(path): """Test whether a path is a mount point""" if islink(path): # A symlink can never be a mount point return False try: s1 = os.lstat(path) s2 = os.lstat(join(path, '..')) except os.error: return False # It doesn't exist -- so not a mount point :-) 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 # Directory tree walk. # For each directory under top (including top itself, but excluding # '.' and '..'), func(arg, dirname, filenames) is called, where # dirname is the name of the directory and filenames is the list # of files (and subdirectories etc.) in the directory. # The func may modify the filenames list, to implement a filter, # or to impose a different order of visiting.
def islink(s): """Return true if the pathname refers to a symbolic link.""" try: import Carbon.File return Carbon.File.ResolveAliasFile(s, 0)[2] except: return False # Is `stat`/`lstat` a meaningful difference on the Mac? This is safe in any # case.
def lexists(path): """Test whether a path exists. Returns True for broken symbolic links""" try: st = os.lstat(path) except os.error: return False return True
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()
def hashPath(self, path): path = os.fsencode(path) try: s = os.lstat(path) except OSError as err: logging.getLogger(__name__).warning("Cannot stat '%s': %s", path, str(err)) return b'' self.__index.open() try: return self.__hashEntry(path, b'', s) finally: self.__index.close()
def _get_default_cache_dir(self): def _unsafe_dir(): raise RuntimeError('Cannot determine safe temp directory. You ' 'need to explicitly provide one.') tmpdir = tempfile.gettempdir() # On windows the temporary directory is used specific unless # explicitly forced otherwise. We can just use that. if os.name == 'nt': return tmpdir if not hasattr(os, 'getuid'): _unsafe_dir() dirname = '_jinja2-cache-%d' % os.getuid() actual_dir = os.path.join(tmpdir, dirname) try: os.mkdir(actual_dir, stat.S_IRWXU) except OSError as e: if e.errno != errno.EEXIST: raise try: os.chmod(actual_dir, stat.S_IRWXU) actual_dir_stat = os.lstat(actual_dir) if actual_dir_stat.st_uid != os.getuid() \ or not stat.S_ISDIR(actual_dir_stat.st_mode) \ or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU: _unsafe_dir() except OSError as e: if e.errno != errno.EEXIST: raise actual_dir_stat = os.lstat(actual_dir) if actual_dir_stat.st_uid != os.getuid() \ or not stat.S_ISDIR(actual_dir_stat.st_mode) \ or stat.S_IMODE(actual_dir_stat.st_mode) != stat.S_IRWXU: _unsafe_dir() return actual_dir
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())
def timestamp(fname,link = None): try: return (os.lstat if link else os.stat)(fname)[STAT_MTIME] except OSError: return 0
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.)
def _set_version(self): self.version = record.get_version(self.path, self.name) if self.version is None and self.persisted(): self.version = int(os.lstat(self.path).st_mtime) record.set_version(self.path, self.name, self.version)
def islink(self): st = self.path.lstat() return S_ISLNK(self._osstatresult.st_mode)
def _stat(self): try: return self._statcache except AttributeError: try: self._statcache = self.path.stat() except py.error.ELOOP: self._statcache = self.path.lstat() return self._statcache
def link(self): st = self.path.lstat() return S_ISLNK(st.mode)
def lstat(self): """ Return an os.lstat() tuple. """ return Stat(self, py.error.checked_call(os.lstat, self.strpath))
def next(self): try: f = self.files.pop(0) except IndexError: raise StopIteration else: s = self.server.avatar._runAsUser(os.lstat, os.path.join(self.dir, f)) longname = lsLine(f, s) attrs = self.server._getAttrs(s) return (f, longname, attrs)