mirror of
https://github.com/python/cpython.git
synced 2025-09-27 02:39:58 +00:00
GH-119169: Simplify os.walk()
exception handling (#121435)
Handle errors from `os.scandir()` and `ScandirIterator` similarly, which lets us loop over directory entries with `for`.
This commit is contained in:
parent
5289550b33
commit
db00fee3a2
2 changed files with 35 additions and 50 deletions
26
Lib/os.py
26
Lib/os.py
|
@ -373,26 +373,8 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
|
||||||
# minor reason when (say) a thousand readable directories are still
|
# minor reason when (say) a thousand readable directories are still
|
||||||
# left to visit.
|
# left to visit.
|
||||||
try:
|
try:
|
||||||
scandir_it = scandir(top)
|
with scandir(top) as entries:
|
||||||
except OSError as error:
|
for entry in entries:
|
||||||
if onerror is not None:
|
|
||||||
onerror(error)
|
|
||||||
continue
|
|
||||||
|
|
||||||
cont = False
|
|
||||||
with scandir_it:
|
|
||||||
while True:
|
|
||||||
try:
|
|
||||||
try:
|
|
||||||
entry = next(scandir_it)
|
|
||||||
except StopIteration:
|
|
||||||
break
|
|
||||||
except OSError as error:
|
|
||||||
if onerror is not None:
|
|
||||||
onerror(error)
|
|
||||||
cont = True
|
|
||||||
break
|
|
||||||
|
|
||||||
try:
|
try:
|
||||||
if followlinks is _walk_symlinks_as_files:
|
if followlinks is _walk_symlinks_as_files:
|
||||||
is_dir = entry.is_dir(follow_symlinks=False) and not entry.is_junction()
|
is_dir = entry.is_dir(follow_symlinks=False) and not entry.is_junction()
|
||||||
|
@ -425,7 +407,9 @@ def walk(top, topdown=True, onerror=None, followlinks=False):
|
||||||
|
|
||||||
if walk_into:
|
if walk_into:
|
||||||
walk_dirs.append(entry.path)
|
walk_dirs.append(entry.path)
|
||||||
if cont:
|
except OSError as error:
|
||||||
|
if onerror is not None:
|
||||||
|
onerror(error)
|
||||||
continue
|
continue
|
||||||
|
|
||||||
if topdown:
|
if topdown:
|
||||||
|
|
|
@ -0,0 +1 @@
|
||||||
|
Slightly speed up :func:`os.walk` by simplifying exception handling.
|
Loading…
Add table
Add a link
Reference in a new issue