os.walk onerror参数问题 [英] Issue with os.walk onerror argument

查看:73
本文介绍了os.walk onerror参数问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我到处搜索,但是找不到关于os.walk(onerror)工作原理的解释.

i searched everywhere but I could not find one explanation on how os.walk(onerror) works.

os.walk谨慎地忽略了listdir()错误,但我至少需要接收警报,最好是引起此错误的目录路径.我应该如何设置该参数?

os.walk is defautly ignoring listdir() errors but I need to recieve at least alert, in better case path of directory which caused this error. How should I set up this argument?

感谢您的帮助.

推荐答案

错误处理程序应该是可调用的.它将使用一个参数(异常实例)进行调用.

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 默认情况下忽略错误是设计使然.这样,即使在例如由于权限不足而无法列出步行中遇到的一个子目录之后,步行也可以继续遍历其他目录.

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.

在处理异常实例时,您感兴趣的所有信息都可能包含在 exception_instance.args type(exception_instance)中.由于它是一个 OSError (或子类型),因此 errno 将是一个有用的属性.

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.

您可以与stdlib的常量进行比较 errno 模块.例如,拒绝权限是 errno.EACCES (13).如果您尝试将/root 列为普通用户,就会出现此错误.

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.

这篇关于os.walk onerror参数问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆