How to get the errno of an IOError?

杀马特。学长 韩版系。学妹 提交于 2019-12-02 19:06:49

The Exception has an errno attribute:

try:
    fp = open("nothere")
except IOError as e:
    print(e.errno)
    print(e)

Here's how you can do it. Also see the errno module and os.strerror function for some utilities.

import os, errno

try:
    f = open('asdfasdf', 'r')
except IOError as ioex:
    print 'errno:', ioex.errno
    print 'err code:', errno.errorcode[ioex.errno]
    print 'err message:', os.strerror(ioex.errno)

For more information on IOError attributes, see the base class EnvironmentError:

try:
    fp = open("nothere")
except IOError as err:
    print err.errno 
    print err.strerror

Different exceptions can also be tested for in the same 'except' clause, e.g.

try:
    serial_port.open()
except (AttributeError, SerialException) as e:
    print('cannot open serial port: {}'.format(e))
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!