python - 如何获取 Exception OSError 的第三个参数?

标签 python

来自Python document :

For backwards compatibility, if three arguments are passed, the args attribute contains only a 2-tuple of the first two constructor arguments.

那么我们如何处理第三个参数,例如“无效路径”?

try:
    open('invalid path')
except OSError as e:
    error = e
    print(error.args[0],error.args[1])
    print(e)

结果:

2 No such file or directory
[Errno 2] No such file or directory: 'invalid path'

最佳答案

来自相同的文档:

For exceptions that involve a file system path (such as open() or os.unlink()), filename is the file name passed to the function. For functions that involve two file system paths (such as os.rename()), filename2 corresponds to the second file name passed to the function.

因此,您只需执行 error.filename 即可,因为 filename 是一个可选参数,仅针对某些类型的错误传递该参数。

要进行一刀切检查,您可以使用 hasattr:

if hasattr(error, 'filename'):
    print(error.filename)

关于python - 如何获取 Exception OSError 的第三个参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37939508/

相关文章:

python - 使用字符值在 Pandas 中创建新行

python - 将字符串返回到 SWIG python 接口(interface)的最佳方法是什么?

python - 无法使用 pyaudio 在 Mac Mojave 上访问麦克风

python - NumPy:3D 数组的 1D 插值

python - 在 Xcode 下运行 virtualenv python

python - Django fixtures 和 OneToOneField

python - 反向传播时为 Keras 定制导数?

python - 打开python文件时如何修复Jupyter扩展激活失败?

python - 如何使用 python 将作业安排到客户端系统?

python - opencv imutils 调整视频流大小