与 IOError 相关的 Python 错误号是否稳定? [英] Are Python error numbers associated with IOError stable?

查看:48
本文介绍了与 IOError 相关的 Python 错误号是否稳定?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I want to move a file, but in the case it is not found I should just ignore it. In all other cases the exception should be propagated. I have the following piece of Python code:

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

errno == 2 是具有没有这样的文件或目录"描述的那个.我想知道这是否跨 Python 版本和平台等稳定.

errno == 2 is the one, that has 'No such file or directory' description. I wonder if this is stable across Python versions and platforms, and etc.

推荐答案

最好使用 errno 模块而不是对值 2 进行硬编码:

It is better to use values from the errno module instead of hardcoding the value 2:

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

这使您的代码不太可能在整数错误值发生变化时中断(尽管这种情况不太可能发生).

This makes your code less likely to break in case the integer error value changes (although that is unlikely to occur).

这篇关于与 IOError 相关的 Python 错误号是否稳定?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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