开发者

OSError's filename attribute unavailable?

I have the following code:

except(OSError) as (errno, strerror, filename):
print "OSError [%d]: %s at %s" % (errno, strerror, filename)

It runs great unless it meets OSError num. 123 (The file name, directory name, or volume label synta开发者_开发百科x is incorrect). then I get the following error at the except code line:

ValueError: need more than 2 values to unpack

It is solved by not using the filename attribute. However my requirements prevent me from not using this attribute.

Is there another way?


I have not seen this kind of Exception handling where you are passing the Exception object's attributes to the as clause.

Normally you handle except ExceptionObject as e and handle the attributes as one would normally handle the attributes of an object.

OSError contains a errno attribute is a numeric error code from errno, and the strerror attribute is the corresponding string and for exceptions that involve a file system path (such as chdir() or unlink()), the exception instance will contain a third attribute, filename, which is the file name passed to the function.

import os
try:
    os.chdir('somenonexistingdir')
except OSError as e:
    print e.errno
    print e.filename
    print e.strerror
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜