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

查看:171
本文介绍了与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天全站免登陆