Pathlib.Path.rglob Fehler ignorieren

Wenn du dir nicht sicher bist, in welchem der anderen Foren du die Frage stellen sollst, dann bist du hier im Forum für allgemeine Fragen sicher richtig.
Antworten
Fire Spike
User
Beiträge: 329
Registriert: Montag 13. Mai 2019, 16:05
Wohnort: Erde

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'
Sirius3
User
Beiträge: 18272
Registriert: Sonntag 21. Oktober 2012, 17:20

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)
Antworten