| 343 | return _walk(fspath(top), topdown, onerror, followlinks) |
| 344 | |
| 345 | def _walk(top, topdown, onerror, followlinks): |
| 346 | dirs = [] |
| 347 | nondirs = [] |
| 348 | walk_dirs = [] |
| 349 | |
| 350 | # We may not have read permission for top, in which case we can't |
| 351 | # get a list of the files the directory contains. os.walk |
| 352 | # always suppressed the exception then, rather than blow up for a |
| 353 | # minor reason when (say) a thousand readable directories are still |
| 354 | # left to visit. That logic is copied here. |
| 355 | try: |
| 356 | # Note that scandir is global in this module due |
| 357 | # to earlier import-*. |
| 358 | scandir_it = scandir(top) |
| 359 | except OSError as error: |
| 360 | if onerror is not None: |
| 361 | onerror(error) |
| 362 | return |
| 363 | |
| 364 | with scandir_it: |
| 365 | while True: |
| 366 | try: |
| 367 | try: |
| 368 | entry = next(scandir_it) |
| 369 | except StopIteration: |
| 370 | break |
| 371 | except OSError as error: |
| 372 | if onerror is not None: |
| 373 | onerror(error) |
| 374 | return |
| 375 | |
| 376 | try: |
| 377 | is_dir = entry.is_dir() |
| 378 | except OSError: |
| 379 | # If is_dir() raises an OSError, consider that the entry is not |
| 380 | # a directory, same behaviour than os.path.isdir(). |
| 381 | is_dir = False |
| 382 | |
| 383 | if is_dir: |
| 384 | dirs.append(entry.name) |
| 385 | else: |
| 386 | nondirs.append(entry.name) |
| 387 | |
| 388 | if not topdown and is_dir: |
| 389 | # Bottom-up: recurse into sub-directory, but exclude symlinks to |
| 390 | # directories if followlinks is False |
| 391 | if followlinks: |
| 392 | walk_into = True |
| 393 | else: |
| 394 | try: |
| 395 | is_symlink = entry.is_symlink() |
| 396 | except OSError: |
| 397 | # If is_symlink() raises an OSError, consider that the |
| 398 | # entry is not a symbolic link, same behaviour than |
| 399 | # os.path.islink(). |
| 400 | is_symlink = False |
| 401 | walk_into = not is_symlink |
| 402 | |