gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 03:11:14 25 4
gpt4 key购买 nike

来自 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 是一个可选的 arg,它只针对特定类型的错误传递。

要进行一劳永逸的检查,您可以使用hasattr:

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

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

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com