C语言中有perror和errno函数,它们会打印并保存最近遇到的错误。这在进行文件io操作时很方便,因为我不需要对每个无法打开的文件使用fstat()作为fopen()的参数来向用户呈现调用失败的原因。
我想知道在Python中优雅地处理IOError异常时获取errno的正确方法是什么?
In [1]: fp = open("/notthere") --------------------------------------------------------------------------- IOError Traceback (most recent call last)
/home/mugen/ in ()
IOError: [Errno 2] No such file or directory: '/notthere'
In [2]: fp = open("test/testfile") --------------------------------------------------------------------------- IOError Traceback (most recent call last)
/home/mugen/ in ()
IOError: [Errno 13] Permission denied: 'test/testfile'
In [5]: try: ...: fp = open("nothere") ...: except IOError: ...: print "This failed for some reason..." ...: ...: This failed for some reason...
ioex.strerror
似乎是os.strerror(ioex.errno)
(Python 2.7)的等效方法。 - Dannid