【问题标题】:Are Python error numbers associated with IOError stable?与 IOError 相关的 Python 错误编号是否稳定?
【发布时间】:2012-08-30 06:53:51
【问题描述】:

我想移动一个文件,但如果找不到它,我应该忽略它。在所有其他情况下,应传播异常。我有以下一段 Python 代码:

try:
    shutil.move(old_path, new_path)
except IOError as e:
    if e.errno != 2: raise e

errno == 2 是具有“没有这样的文件或目录”描述的那个。我想知道这在 Python 版本和平台等方面是否稳定。

【问题讨论】:

    标签: python api exception error-handling errno


    【解决方案1】:

    最好使用来自errno 模块的值,而不是硬编码值2

    try:
        shutil.move(old_path, new_path)
    except IOError as e:
        if e.errno != errno.ENOENT: raise e
    

    这使您的代码在整数错误值更改时不太可能中断(尽管这不太可能发生)。

    【讨论】:

    • “不太可能”是一种轻描淡写的说法 - 会破坏的程序数量令人难以置信,它永远不会发生。但总是首选使用符号而不是幻数。
    • 非常感谢。我什至不知道,这样的模块存在。这正是我想要的。
    猜你喜欢
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多