来自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/