Edit File by line
/home/barbar84/public_h.../wp-conte.../plugins/sujqvwi/AnonR/anonr.TX.../opt/imh-pyth.../lib/python3....
File: os.py
r"""OS routines for NT or Posix depending on what system we're on.
[0] Fix | Delete
[1] Fix | Delete
This exports:
[2] Fix | Delete
- all functions from posix or nt, e.g. unlink, stat, etc.
[3] Fix | Delete
- os.path is either posixpath or ntpath
[4] Fix | Delete
- os.name is either 'posix' or 'nt'
[5] Fix | Delete
- os.curdir is a string representing the current directory (always '.')
[6] Fix | Delete
- os.pardir is a string representing the parent directory (always '..')
[7] Fix | Delete
- os.sep is the (or a most common) pathname separator ('/' or '\\')
[8] Fix | Delete
- os.extsep is the extension separator (always '.')
[9] Fix | Delete
- os.altsep is the alternate pathname separator (None or '/')
[10] Fix | Delete
- os.pathsep is the component separator used in $PATH etc
[11] Fix | Delete
- os.linesep is the line separator in text files ('\r' or '\n' or '\r\n')
[12] Fix | Delete
- os.defpath is the default search path for executables
[13] Fix | Delete
- os.devnull is the file path of the null device ('/dev/null', etc.)
[14] Fix | Delete
[15] Fix | Delete
Programs that import and use 'os' stand a better chance of being
[16] Fix | Delete
portable between different platforms. Of course, they must then
[17] Fix | Delete
only use functions that are defined by all platforms (e.g., unlink
[18] Fix | Delete
and opendir), and leave all pathname manipulation to os.path
[19] Fix | Delete
(e.g., split and join).
[20] Fix | Delete
"""
[21] Fix | Delete
[22] Fix | Delete
#'
[23] Fix | Delete
import abc
[24] Fix | Delete
import sys
[25] Fix | Delete
import stat as st
[26] Fix | Delete
[27] Fix | Delete
from _collections_abc import _check_methods
[28] Fix | Delete
[29] Fix | Delete
GenericAlias = type(list[int])
[30] Fix | Delete
[31] Fix | Delete
_names = sys.builtin_module_names
[32] Fix | Delete
[33] Fix | Delete
# Note: more names are added to __all__ later.
[34] Fix | Delete
__all__ = ["altsep", "curdir", "pardir", "sep", "pathsep", "linesep",
[35] Fix | Delete
"defpath", "name", "path", "devnull", "SEEK_SET", "SEEK_CUR",
[36] Fix | Delete
"SEEK_END", "fsencode", "fsdecode", "get_exec_path", "fdopen",
[37] Fix | Delete
"popen", "extsep"]
[38] Fix | Delete
[39] Fix | Delete
def _exists(name):
[40] Fix | Delete
return name in globals()
[41] Fix | Delete
[42] Fix | Delete
def _get_exports_list(module):
[43] Fix | Delete
try:
[44] Fix | Delete
return list(module.__all__)
[45] Fix | Delete
except AttributeError:
[46] Fix | Delete
return [n for n in dir(module) if n[0] != '_']
[47] Fix | Delete
[48] Fix | Delete
# Any new dependencies of the os module and/or changes in path separator
[49] Fix | Delete
# requires updating importlib as well.
[50] Fix | Delete
if 'posix' in _names:
[51] Fix | Delete
name = 'posix'
[52] Fix | Delete
linesep = '\n'
[53] Fix | Delete
from posix import *
[54] Fix | Delete
try:
[55] Fix | Delete
from posix import _exit
[56] Fix | Delete
__all__.append('_exit')
[57] Fix | Delete
except ImportError:
[58] Fix | Delete
pass
[59] Fix | Delete
import posixpath as path
[60] Fix | Delete
[61] Fix | Delete
try:
[62] Fix | Delete
from posix import _have_functions
[63] Fix | Delete
except ImportError:
[64] Fix | Delete
pass
[65] Fix | Delete
[66] Fix | Delete
import posix
[67] Fix | Delete
__all__.extend(_get_exports_list(posix))
[68] Fix | Delete
del posix
[69] Fix | Delete
[70] Fix | Delete
elif 'nt' in _names:
[71] Fix | Delete
name = 'nt'
[72] Fix | Delete
linesep = '\r\n'
[73] Fix | Delete
from nt import *
[74] Fix | Delete
try:
[75] Fix | Delete
from nt import _exit
[76] Fix | Delete
__all__.append('_exit')
[77] Fix | Delete
except ImportError:
[78] Fix | Delete
pass
[79] Fix | Delete
import ntpath as path
[80] Fix | Delete
[81] Fix | Delete
import nt
[82] Fix | Delete
__all__.extend(_get_exports_list(nt))
[83] Fix | Delete
del nt
[84] Fix | Delete
[85] Fix | Delete
try:
[86] Fix | Delete
from nt import _have_functions
[87] Fix | Delete
except ImportError:
[88] Fix | Delete
pass
[89] Fix | Delete
[90] Fix | Delete
else:
[91] Fix | Delete
raise ImportError('no os specific module found')
[92] Fix | Delete
[93] Fix | Delete
sys.modules['os.path'] = path
[94] Fix | Delete
from os.path import (curdir, pardir, sep, pathsep, defpath, extsep, altsep,
[95] Fix | Delete
devnull)
[96] Fix | Delete
[97] Fix | Delete
del _names
[98] Fix | Delete
[99] Fix | Delete
[100] Fix | Delete
if _exists("_have_functions"):
[101] Fix | Delete
_globals = globals()
[102] Fix | Delete
def _add(str, fn):
[103] Fix | Delete
if (fn in _globals) and (str in _have_functions):
[104] Fix | Delete
_set.add(_globals[fn])
[105] Fix | Delete
[106] Fix | Delete
_set = set()
[107] Fix | Delete
_add("HAVE_FACCESSAT", "access")
[108] Fix | Delete
_add("HAVE_FCHMODAT", "chmod")
[109] Fix | Delete
_add("HAVE_FCHOWNAT", "chown")
[110] Fix | Delete
_add("HAVE_FSTATAT", "stat")
[111] Fix | Delete
_add("HAVE_FUTIMESAT", "utime")
[112] Fix | Delete
_add("HAVE_LINKAT", "link")
[113] Fix | Delete
_add("HAVE_MKDIRAT", "mkdir")
[114] Fix | Delete
_add("HAVE_MKFIFOAT", "mkfifo")
[115] Fix | Delete
_add("HAVE_MKNODAT", "mknod")
[116] Fix | Delete
_add("HAVE_OPENAT", "open")
[117] Fix | Delete
_add("HAVE_READLINKAT", "readlink")
[118] Fix | Delete
_add("HAVE_RENAMEAT", "rename")
[119] Fix | Delete
_add("HAVE_SYMLINKAT", "symlink")
[120] Fix | Delete
_add("HAVE_UNLINKAT", "unlink")
[121] Fix | Delete
_add("HAVE_UNLINKAT", "rmdir")
[122] Fix | Delete
_add("HAVE_UTIMENSAT", "utime")
[123] Fix | Delete
supports_dir_fd = _set
[124] Fix | Delete
[125] Fix | Delete
_set = set()
[126] Fix | Delete
_add("HAVE_FACCESSAT", "access")
[127] Fix | Delete
supports_effective_ids = _set
[128] Fix | Delete
[129] Fix | Delete
_set = set()
[130] Fix | Delete
_add("HAVE_FCHDIR", "chdir")
[131] Fix | Delete
_add("HAVE_FCHMOD", "chmod")
[132] Fix | Delete
_add("HAVE_FCHOWN", "chown")
[133] Fix | Delete
_add("HAVE_FDOPENDIR", "listdir")
[134] Fix | Delete
_add("HAVE_FDOPENDIR", "scandir")
[135] Fix | Delete
_add("HAVE_FEXECVE", "execve")
[136] Fix | Delete
_set.add(stat) # fstat always works
[137] Fix | Delete
_add("HAVE_FTRUNCATE", "truncate")
[138] Fix | Delete
_add("HAVE_FUTIMENS", "utime")
[139] Fix | Delete
_add("HAVE_FUTIMES", "utime")
[140] Fix | Delete
_add("HAVE_FPATHCONF", "pathconf")
[141] Fix | Delete
if _exists("statvfs") and _exists("fstatvfs"): # mac os x10.3
[142] Fix | Delete
_add("HAVE_FSTATVFS", "statvfs")
[143] Fix | Delete
supports_fd = _set
[144] Fix | Delete
[145] Fix | Delete
_set = set()
[146] Fix | Delete
_add("HAVE_FACCESSAT", "access")
[147] Fix | Delete
# Some platforms don't support lchmod(). Often the function exists
[148] Fix | Delete
# anyway, as a stub that always returns ENOSUP or perhaps EOPNOTSUPP.
[149] Fix | Delete
# (No, I don't know why that's a good design.) ./configure will detect
[150] Fix | Delete
# this and reject it--so HAVE_LCHMOD still won't be defined on such
[151] Fix | Delete
# platforms. This is Very Helpful.
[152] Fix | Delete
#
[153] Fix | Delete
# However, sometimes platforms without a working lchmod() *do* have
[154] Fix | Delete
# fchmodat(). (Examples: Linux kernel 3.2 with glibc 2.15,
[155] Fix | Delete
# OpenIndiana 3.x.) And fchmodat() has a flag that theoretically makes
[156] Fix | Delete
# it behave like lchmod(). So in theory it would be a suitable
[157] Fix | Delete
# replacement for lchmod(). But when lchmod() doesn't work, fchmodat()'s
[158] Fix | Delete
# flag doesn't work *either*. Sadly ./configure isn't sophisticated
[159] Fix | Delete
# enough to detect this condition--it only determines whether or not
[160] Fix | Delete
# fchmodat() minimally works.
[161] Fix | Delete
#
[162] Fix | Delete
# Therefore we simply ignore fchmodat() when deciding whether or not
[163] Fix | Delete
# os.chmod supports follow_symlinks. Just checking lchmod() is
[164] Fix | Delete
# sufficient. After all--if you have a working fchmodat(), your
[165] Fix | Delete
# lchmod() almost certainly works too.
[166] Fix | Delete
#
[167] Fix | Delete
# _add("HAVE_FCHMODAT", "chmod")
[168] Fix | Delete
_add("HAVE_FCHOWNAT", "chown")
[169] Fix | Delete
_add("HAVE_FSTATAT", "stat")
[170] Fix | Delete
_add("HAVE_LCHFLAGS", "chflags")
[171] Fix | Delete
_add("HAVE_LCHMOD", "chmod")
[172] Fix | Delete
if _exists("lchown"): # mac os x10.3
[173] Fix | Delete
_add("HAVE_LCHOWN", "chown")
[174] Fix | Delete
_add("HAVE_LINKAT", "link")
[175] Fix | Delete
_add("HAVE_LUTIMES", "utime")
[176] Fix | Delete
_add("HAVE_LSTAT", "stat")
[177] Fix | Delete
_add("HAVE_FSTATAT", "stat")
[178] Fix | Delete
_add("HAVE_UTIMENSAT", "utime")
[179] Fix | Delete
_add("MS_WINDOWS", "stat")
[180] Fix | Delete
supports_follow_symlinks = _set
[181] Fix | Delete
[182] Fix | Delete
del _set
[183] Fix | Delete
del _have_functions
[184] Fix | Delete
del _globals
[185] Fix | Delete
del _add
[186] Fix | Delete
[187] Fix | Delete
[188] Fix | Delete
# Python uses fixed values for the SEEK_ constants; they are mapped
[189] Fix | Delete
# to native constants if necessary in posixmodule.c
[190] Fix | Delete
# Other possible SEEK values are directly imported from posixmodule.c
[191] Fix | Delete
SEEK_SET = 0
[192] Fix | Delete
SEEK_CUR = 1
[193] Fix | Delete
SEEK_END = 2
[194] Fix | Delete
[195] Fix | Delete
# Super directory utilities.
[196] Fix | Delete
# (Inspired by Eric Raymond; the doc strings are mostly his)
[197] Fix | Delete
[198] Fix | Delete
def makedirs(name, mode=0o777, exist_ok=False):
[199] Fix | Delete
"""makedirs(name [, mode=0o777][, exist_ok=False])
[200] Fix | Delete
[201] Fix | Delete
Super-mkdir; create a leaf directory and all intermediate ones. Works like
[202] Fix | Delete
mkdir, except that any intermediate path segment (not just the rightmost)
[203] Fix | Delete
will be created if it does not exist. If the target directory already
[204] Fix | Delete
exists, raise an OSError if exist_ok is False. Otherwise no exception is
[205] Fix | Delete
raised. This is recursive.
[206] Fix | Delete
[207] Fix | Delete
"""
[208] Fix | Delete
head, tail = path.split(name)
[209] Fix | Delete
if not tail:
[210] Fix | Delete
head, tail = path.split(head)
[211] Fix | Delete
if head and tail and not path.exists(head):
[212] Fix | Delete
try:
[213] Fix | Delete
makedirs(head, exist_ok=exist_ok)
[214] Fix | Delete
except FileExistsError:
[215] Fix | Delete
# Defeats race condition when another thread created the path
[216] Fix | Delete
pass
[217] Fix | Delete
cdir = curdir
[218] Fix | Delete
if isinstance(tail, bytes):
[219] Fix | Delete
cdir = bytes(curdir, 'ASCII')
[220] Fix | Delete
if tail == cdir: # xxx/newdir/. exists if xxx/newdir exists
[221] Fix | Delete
return
[222] Fix | Delete
try:
[223] Fix | Delete
mkdir(name, mode)
[224] Fix | Delete
except OSError:
[225] Fix | Delete
# Cannot rely on checking for EEXIST, since the operating system
[226] Fix | Delete
# could give priority to other errors like EACCES or EROFS
[227] Fix | Delete
if not exist_ok or not path.isdir(name):
[228] Fix | Delete
raise
[229] Fix | Delete
[230] Fix | Delete
def removedirs(name):
[231] Fix | Delete
"""removedirs(name)
[232] Fix | Delete
[233] Fix | Delete
Super-rmdir; remove a leaf directory and all empty intermediate
[234] Fix | Delete
ones. Works like rmdir except that, if the leaf directory is
[235] Fix | Delete
successfully removed, directories corresponding to rightmost path
[236] Fix | Delete
segments will be pruned away until either the whole path is
[237] Fix | Delete
consumed or an error occurs. Errors during this latter phase are
[238] Fix | Delete
ignored -- they generally mean that a directory was not empty.
[239] Fix | Delete
[240] Fix | Delete
"""
[241] Fix | Delete
rmdir(name)
[242] Fix | Delete
head, tail = path.split(name)
[243] Fix | Delete
if not tail:
[244] Fix | Delete
head, tail = path.split(head)
[245] Fix | Delete
while head and tail:
[246] Fix | Delete
try:
[247] Fix | Delete
rmdir(head)
[248] Fix | Delete
except OSError:
[249] Fix | Delete
break
[250] Fix | Delete
head, tail = path.split(head)
[251] Fix | Delete
[252] Fix | Delete
def renames(old, new):
[253] Fix | Delete
"""renames(old, new)
[254] Fix | Delete
[255] Fix | Delete
Super-rename; create directories as necessary and delete any left
[256] Fix | Delete
empty. Works like rename, except creation of any intermediate
[257] Fix | Delete
directories needed to make the new pathname good is attempted
[258] Fix | Delete
first. After the rename, directories corresponding to rightmost
[259] Fix | Delete
path segments of the old name will be pruned until either the
[260] Fix | Delete
whole path is consumed or a nonempty directory is found.
[261] Fix | Delete
[262] Fix | Delete
Note: this function can fail with the new directory structure made
[263] Fix | Delete
if you lack permissions needed to unlink the leaf directory or
[264] Fix | Delete
file.
[265] Fix | Delete
[266] Fix | Delete
"""
[267] Fix | Delete
head, tail = path.split(new)
[268] Fix | Delete
if head and tail and not path.exists(head):
[269] Fix | Delete
makedirs(head)
[270] Fix | Delete
rename(old, new)
[271] Fix | Delete
head, tail = path.split(old)
[272] Fix | Delete
if head and tail:
[273] Fix | Delete
try:
[274] Fix | Delete
removedirs(head)
[275] Fix | Delete
except OSError:
[276] Fix | Delete
pass
[277] Fix | Delete
[278] Fix | Delete
__all__.extend(["makedirs", "removedirs", "renames"])
[279] Fix | Delete
[280] Fix | Delete
def walk(top, topdown=True, onerror=None, followlinks=False):
[281] Fix | Delete
"""Directory tree generator.
[282] Fix | Delete
[283] Fix | Delete
For each directory in the directory tree rooted at top (including top
[284] Fix | Delete
itself, but excluding '.' and '..'), yields a 3-tuple
[285] Fix | Delete
[286] Fix | Delete
dirpath, dirnames, filenames
[287] Fix | Delete
[288] Fix | Delete
dirpath is a string, the path to the directory. dirnames is a list of
[289] Fix | Delete
the names of the subdirectories in dirpath (excluding '.' and '..').
[290] Fix | Delete
filenames is a list of the names of the non-directory files in dirpath.
[291] Fix | Delete
Note that the names in the lists are just names, with no path components.
[292] Fix | Delete
To get a full path (which begins with top) to a file or directory in
[293] Fix | Delete
dirpath, do os.path.join(dirpath, name).
[294] Fix | Delete
[295] Fix | Delete
If optional arg 'topdown' is true or not specified, the triple for a
[296] Fix | Delete
directory is generated before the triples for any of its subdirectories
[297] Fix | Delete
(directories are generated top down). If topdown is false, the triple
[298] Fix | Delete
for a directory is generated after the triples for all of its
[299] Fix | Delete
subdirectories (directories are generated bottom up).
[300] Fix | Delete
[301] Fix | Delete
When topdown is true, the caller can modify the dirnames list in-place
[302] Fix | Delete
(e.g., via del or slice assignment), and walk will only recurse into the
[303] Fix | Delete
subdirectories whose names remain in dirnames; this can be used to prune the
[304] Fix | Delete
search, or to impose a specific order of visiting. Modifying dirnames when
[305] Fix | Delete
topdown is false has no effect on the behavior of os.walk(), since the
[306] Fix | Delete
directories in dirnames have already been generated by the time dirnames
[307] Fix | Delete
itself is generated. No matter the value of topdown, the list of
[308] Fix | Delete
subdirectories is retrieved before the tuples for the directory and its
[309] Fix | Delete
subdirectories are generated.
[310] Fix | Delete
[311] Fix | Delete
By default errors from the os.scandir() call are ignored. If
[312] Fix | Delete
optional arg 'onerror' is specified, it should be a function; it
[313] Fix | Delete
will be called with one argument, an OSError instance. It can
[314] Fix | Delete
report the error to continue with the walk, or raise the exception
[315] Fix | Delete
to abort the walk. Note that the filename is available as the
[316] Fix | Delete
filename attribute of the exception object.
[317] Fix | Delete
[318] Fix | Delete
By default, os.walk does not follow symbolic links to subdirectories on
[319] Fix | Delete
systems that support them. In order to get this functionality, set the
[320] Fix | Delete
optional argument 'followlinks' to true.
[321] Fix | Delete
[322] Fix | Delete
Caution: if you pass a relative pathname for top, don't change the
[323] Fix | Delete
current working directory between resumptions of walk. walk never
[324] Fix | Delete
changes the current directory, and assumes that the client doesn't
[325] Fix | Delete
either.
[326] Fix | Delete
[327] Fix | Delete
Example:
[328] Fix | Delete
[329] Fix | Delete
import os
[330] Fix | Delete
from os.path import join, getsize
[331] Fix | Delete
for root, dirs, files in os.walk('python/Lib/email'):
[332] Fix | Delete
print(root, "consumes", end="")
[333] Fix | Delete
print(sum(getsize(join(root, name)) for name in files), end="")
[334] Fix | Delete
print("bytes in", len(files), "non-directory files")
[335] Fix | Delete
if 'CVS' in dirs:
[336] Fix | Delete
dirs.remove('CVS') # don't visit CVS directories
[337] Fix | Delete
[338] Fix | Delete
"""
[339] Fix | Delete
sys.audit("os.walk", top, topdown, onerror, followlinks)
[340] Fix | Delete
return _walk(fspath(top), topdown, onerror, followlinks)
[341] Fix | Delete
[342] Fix | Delete
def _walk(top, topdown, onerror, followlinks):
[343] Fix | Delete
dirs = []
[344] Fix | Delete
nondirs = []
[345] Fix | Delete
walk_dirs = []
[346] Fix | Delete
[347] Fix | Delete
# We may not have read permission for top, in which case we can't
[348] Fix | Delete
# get a list of the files the directory contains. os.walk
[349] Fix | Delete
# always suppressed the exception then, rather than blow up for a
[350] Fix | Delete
# minor reason when (say) a thousand readable directories are still
[351] Fix | Delete
# left to visit. That logic is copied here.
[352] Fix | Delete
try:
[353] Fix | Delete
# Note that scandir is global in this module due
[354] Fix | Delete
# to earlier import-*.
[355] Fix | Delete
scandir_it = scandir(top)
[356] Fix | Delete
except OSError as error:
[357] Fix | Delete
if onerror is not None:
[358] Fix | Delete
onerror(error)
[359] Fix | Delete
return
[360] Fix | Delete
[361] Fix | Delete
with scandir_it:
[362] Fix | Delete
while True:
[363] Fix | Delete
try:
[364] Fix | Delete
try:
[365] Fix | Delete
entry = next(scandir_it)
[366] Fix | Delete
except StopIteration:
[367] Fix | Delete
break
[368] Fix | Delete
except OSError as error:
[369] Fix | Delete
if onerror is not None:
[370] Fix | Delete
onerror(error)
[371] Fix | Delete
return
[372] Fix | Delete
[373] Fix | Delete
try:
[374] Fix | Delete
is_dir = entry.is_dir()
[375] Fix | Delete
except OSError:
[376] Fix | Delete
# If is_dir() raises an OSError, consider that the entry is not
[377] Fix | Delete
# a directory, same behaviour than os.path.isdir().
[378] Fix | Delete
is_dir = False
[379] Fix | Delete
[380] Fix | Delete
if is_dir:
[381] Fix | Delete
dirs.append(entry.name)
[382] Fix | Delete
else:
[383] Fix | Delete
nondirs.append(entry.name)
[384] Fix | Delete
[385] Fix | Delete
if not topdown and is_dir:
[386] Fix | Delete
# Bottom-up: recurse into sub-directory, but exclude symlinks to
[387] Fix | Delete
# directories if followlinks is False
[388] Fix | Delete
if followlinks:
[389] Fix | Delete
walk_into = True
[390] Fix | Delete
else:
[391] Fix | Delete
try:
[392] Fix | Delete
is_symlink = entry.is_symlink()
[393] Fix | Delete
except OSError:
[394] Fix | Delete
# If is_symlink() raises an OSError, consider that the
[395] Fix | Delete
# entry is not a symbolic link, same behaviour than
[396] Fix | Delete
# os.path.islink().
[397] Fix | Delete
is_symlink = False
[398] Fix | Delete
walk_into = not is_symlink
[399] Fix | Delete
[400] Fix | Delete
if walk_into:
[401] Fix | Delete
walk_dirs.append(entry.path)
[402] Fix | Delete
[403] Fix | Delete
# Yield before recursion if going top down
[404] Fix | Delete
if topdown:
[405] Fix | Delete
yield top, dirs, nondirs
[406] Fix | Delete
[407] Fix | Delete
# Recurse into sub-directories
[408] Fix | Delete
islink, join = path.islink, path.join
[409] Fix | Delete
for dirname in dirs:
[410] Fix | Delete
new_path = join(top, dirname)
[411] Fix | Delete
# Issue #23605: os.path.islink() is used instead of caching
[412] Fix | Delete
# entry.is_symlink() result during the loop on os.scandir() because
[413] Fix | Delete
# the caller can replace the directory entry during the "yield"
[414] Fix | Delete
# above.
[415] Fix | Delete
if followlinks or not islink(new_path):
[416] Fix | Delete
yield from _walk(new_path, topdown, onerror, followlinks)
[417] Fix | Delete
else:
[418] Fix | Delete
# Recurse into sub-directories
[419] Fix | Delete
for new_path in walk_dirs:
[420] Fix | Delete
yield from _walk(new_path, topdown, onerror, followlinks)
[421] Fix | Delete
# Yield after recursion if going bottom up
[422] Fix | Delete
yield top, dirs, nondirs
[423] Fix | Delete
[424] Fix | Delete
__all__.append("walk")
[425] Fix | Delete
[426] Fix | Delete
if {open, stat} <= supports_dir_fd and {scandir, stat} <= supports_fd:
[427] Fix | Delete
[428] Fix | Delete
def fwalk(top=".", topdown=True, onerror=None, *, follow_symlinks=False, dir_fd=None):
[429] Fix | Delete
"""Directory tree generator.
[430] Fix | Delete
[431] Fix | Delete
This behaves exactly like walk(), except that it yields a 4-tuple
[432] Fix | Delete
[433] Fix | Delete
dirpath, dirnames, filenames, dirfd
[434] Fix | Delete
[435] Fix | Delete
`dirpath`, `dirnames` and `filenames` are identical to walk() output,
[436] Fix | Delete
and `dirfd` is a file descriptor referring to the directory `dirpath`.
[437] Fix | Delete
[438] Fix | Delete
The advantage of fwalk() over walk() is that it's safe against symlink
[439] Fix | Delete
races (when follow_symlinks is False).
[440] Fix | Delete
[441] Fix | Delete
If dir_fd is not None, it should be a file descriptor open to a directory,
[442] Fix | Delete
and top should be relative; top will then be relative to that directory.
[443] Fix | Delete
(dir_fd is always supported for fwalk.)
[444] Fix | Delete
[445] Fix | Delete
Caution:
[446] Fix | Delete
Since fwalk() yields file descriptors, those are only valid until the
[447] Fix | Delete
next iteration step, so you should dup() them if you want to keep them
[448] Fix | Delete
for a longer period.
[449] Fix | Delete
[450] Fix | Delete
Example:
[451] Fix | Delete
[452] Fix | Delete
import os
[453] Fix | Delete
for root, dirs, files, rootfd in os.fwalk('python/Lib/email'):
[454] Fix | Delete
print(root, "consumes", end="")
[455] Fix | Delete
print(sum(os.stat(name, dir_fd=rootfd).st_size for name in files),
[456] Fix | Delete
end="")
[457] Fix | Delete
print("bytes in", len(files), "non-directory files")
[458] Fix | Delete
if 'CVS' in dirs:
[459] Fix | Delete
dirs.remove('CVS') # don't visit CVS directories
[460] Fix | Delete
"""
[461] Fix | Delete
sys.audit("os.fwalk", top, topdown, onerror, follow_symlinks, dir_fd)
[462] Fix | Delete
if not isinstance(top, int) or not hasattr(top, '__index__'):
[463] Fix | Delete
top = fspath(top)
[464] Fix | Delete
# Note: To guard against symlink races, we use the standard
[465] Fix | Delete
# lstat()/open()/fstat() trick.
[466] Fix | Delete
if not follow_symlinks:
[467] Fix | Delete
orig_st = stat(top, follow_symlinks=False, dir_fd=dir_fd)
[468] Fix | Delete
topfd = open(top, O_RDONLY, dir_fd=dir_fd)
[469] Fix | Delete
try:
[470] Fix | Delete
if (follow_symlinks or (st.S_ISDIR(orig_st.st_mode) and
[471] Fix | Delete
path.samestat(orig_st, stat(topfd)))):
[472] Fix | Delete
yield from _fwalk(topfd, top, isinstance(top, bytes),
[473] Fix | Delete
topdown, onerror, follow_symlinks)
[474] Fix | Delete
finally:
[475] Fix | Delete
close(topfd)
[476] Fix | Delete
[477] Fix | Delete
def _fwalk(topfd, toppath, isbytes, topdown, onerror, follow_symlinks):
[478] Fix | Delete
# Note: This uses O(depth of the directory tree) file descriptors: if
[479] Fix | Delete
# necessary, it can be adapted to only require O(1) FDs, see issue
[480] Fix | Delete
# #13734.
[481] Fix | Delete
[482] Fix | Delete
scandir_it = scandir(topfd)
[483] Fix | Delete
dirs = []
[484] Fix | Delete
nondirs = []
[485] Fix | Delete
entries = None if topdown or follow_symlinks else []
[486] Fix | Delete
for entry in scandir_it:
[487] Fix | Delete
name = entry.name
[488] Fix | Delete
if isbytes:
[489] Fix | Delete
name = fsencode(name)
[490] Fix | Delete
try:
[491] Fix | Delete
if entry.is_dir():
[492] Fix | Delete
dirs.append(name)
[493] Fix | Delete
if entries is not None:
[494] Fix | Delete
entries.append(entry)
[495] Fix | Delete
else:
[496] Fix | Delete
nondirs.append(name)
[497] Fix | Delete
except OSError:
[498] Fix | Delete
try:
[499] Fix | Delete
It is recommended that you Edit text format, this type of Fix handles quite a lot in one request
Function