How to handle OSError: [Errno 36] File name too long

How to handle OSError: [Errno 36] File name too long

在处理尝试创建现有文件或尝试使用不存在的文件时发生的错误时,抛出的 OSErrors 有一个子类(FileExistsErrorFileNotFoundError).当文件名太长时,我找不到用于特殊情况的子类。

确切的错误信息是:

OSError: [Errno 36] File name too long: 'filename'

我想捕获文件名太长时发生的OS错误,但仅当文件名太长时才发生。我 想捕捉其他可能发生的 OSError。有办法实现吗?

编辑: 我知道我可以根据长度检查文件名,但最大文件名长度因 OS 和文件系统而异,我不知道这样看不到 "clean" 解决方案。

只需检查捕获异常的 errno 属性。

try:
    do_something()
except OSError as exc:
    if exc.errno == 36:
        handle_filename_too_long()
    else:
        raise  # re-raise previously caught exception

为了可读性,您可以考虑使用 errno built-in module 中的适当常量而不是硬编码常量。

您可以指定您希望如何捕获特定错误,例如 errno.ENAMETOOLONG:

具体到你的问题...

try:
    # try stuff
except OSError as oserr:
    if oserr.errno != errno.ENAMETOOLONG:
        # ignore
    else:
        # caught...now what?

具体看你的意见...

try:
    # try stuff
except Exception as err:
    # get the name attribute from the exception class
    errname = type(err).__name__
    # get the errno attribute from the exception class
    errnum = err.errno
    if (errname == 'OSError') and (errnum == errno.ENAMETOOLONG):
        # handle specific to OSError [Errno 36]
    else if (errname == 'ExceptionNameHere' and ...:
        # handle specific to blah blah blah
    .
    .
    .
    else:
        raise # if you want to re-raise; otherwise code your ignore

这将抓取由 try 中的错误引起的所有异常。然后它检查 __name__ 是否匹配任何特定的异常以及您要指定的任何其他条件。

您应该知道,如果遇到错误,则无法绕过 except,除非您指定具体的异常。