Skip to content Skip to sidebar Skip to footer

Issue With Os.walk Onerror Argument

i searched everywhere but I could not find one explanation on how os.walk(onerror) works. os.walk is defautly ignoring listdir() errors but I need to recieve at least alert, in bet

Solution 1:

The error handler should be a callable. It will be called with one argument, the exception instance.

def walk_error_handler(exception_instance):
    print("uh-oh!")  # you probably want to do something more substantial here..for root, dirs, files in os.walk(dirname, onerror=walk_error_handler):
    ...

os.walk ignoring errors by default is by design. This allows the walk to continue to traverse other directories even after, for example, one subdirectory encountered in the walk could not be listed due to insufficient permissions.

When handling the exception instance, all the information you are interested in is likely contained in the exception_instance.args and the type(exception_instance). Since it's an OSError (or a subtype), the errno will be a useful attribute.

You can make comparisons against the constants of the stdlib errno module. For example, permission denied is errno.EACCES (13). That's the error you'd get if you tried to list /root as a normal user.

Post a Comment for "Issue With Os.walk Onerror Argument"