Issue With Os.walk Onerror Argument
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"