Seite 1 von 1

Pathlib.Path.rglob Fehler ignorieren

Verfasst: Donnerstag 20. August 2020, 17:07
von Fire Spike
Hallo zusammen.
Ich stehe vor dem folgenden Problem:
Ich versuche das komplette Dateisystem nach Dateien zu untersuchen.
Leider schlägt der folgende Code immer fehl weil es im /proc Verzeichnis sucht, aber es sein kann das ein Ordner nicht mehr existiert.
Wie kann ich das so umschreiben das er den Fehler einfach ignoriert und es ganz normal weiter sucht?

Code: Alles auswählen

from pathlib import Path

excluded_paths = [
    ("proc", 1),
    ("tmp", 1),
    ("sys", 1)
]

for path in Path("/").rglob("*"):
    if path.is_file() and not path.is_symlink():
        for excluded_path in excluded_paths:
            if excluded_path[0] == path.parts[excluded_path[1]]:
                break

            else:
                print(path)
Beispielfehler:

Code: Alles auswählen

Traceback (most recent call last):
  File "main.py", line 9, in <module>
    for path in Path("/").rglob("*"):
  File "/usr/lib/python3.7/pathlib.py", line 1115, in rglob
    for p in selector.select_from(self):
  File "/usr/lib/python3.7/pathlib.py", line 562, in _select_from
    for p in successor_select(starting_point, is_dir, exists, scandir):
  File "/usr/lib/python3.7/pathlib.py", line 519, in _select_from
    entries = list(scandir(parent_path))
OSError: [Errno 22] Invalid argument: '/proc/8433/task/8433/net'

Re: Pathlib.Path.rglob Fehler ignorieren

Verfasst: Donnerstag 20. August 2020, 17:52
von Sirius3
Warum durchsuchst Du überhaupt die Verzeichnisse, die dann doch gleich wieder ausgefiltert werden?

Code: Alles auswählen

from pathlib import Path

def iterpath(basepath="/", excluded_paths=["proc", "tmp", "sys"]):
    for path in Path(basepath).iterdir():
        if path.name not in excluded_paths:
            yield path
            if path.is_dir():
                yield from path.rglob("*")

for path in iterpath("/"):
    if path.is_file() and not path.is_symlink():
        print(path)