2009-07-15 173 views
16

C有perror和errno,它會打印並存儲遇到的最後一個錯誤。這在做文件io時很方便,因爲我不必爲每個失敗的文件fstat()作爲fopen()的參數來向用戶展示調用失敗的原因。Python異常處理

我想知道在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... 

回答

26

例外有一個errno屬性:

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

這裏是你如何能做到這一點。另請參閱errno模塊和os.strerror函數的某些實用程序。

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) 

有關的IOError屬性的更多信息,請參閱基類EnvironmentError:

+1

比接受的答案更好! – RichVel 2013-01-21 19:04:58

+0

`ioex.strerror`似乎相當於`os.strerror(ioex.errno)`(python 2.7) – Dannid 2016-06-28 16:13:14

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