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...
比接受的答案更好! – RichVel 2013-01-21 19:04:58
`ioex.strerror`似乎相當於`os.strerror(ioex.errno)`(python 2.7) – Dannid 2016-06-28 16:13:14