2012-09-30 79 views
0

我想試圖打開一個不存在的文件時要處理的IOError產生。我做的:的Python:錯誤消息解析

try: 
    inputFile = open('nosuchfile', 'r') 
except IOError as exception: 
    print 'error: %s' % (exception) 

這給了我:

error: [Errno 2] No such file or directory: 'nosuchfile' 

但我只有消息,而不是[錯誤2]部分感興趣。所以我改變了我的代碼。

print 'error: %s' % (exception.strerror) 

但現在我得到:

error: No such file or directory 

哪裏的文件名去了?我知道我可以只單獨打印的文件名,但我真的很喜歡這個名字是如何(如果有的話)存儲在例外,但不能在任何其參數(打印exception.errno給予2)。

我使用的版本2.7.3。

回答

4

的文件名保存在,好了,filename屬性:

try: 
    inputFile = open('nosuchfile', 'r') 
except IOError as exception: 
    print ('error: %s: %r' % (exception.strerror, exception.filename)) 
+0

哦,明白了。但是爲什麼當我打印exception.args時沒有顯示呢? –

+0

注意:'exception.strerror'是_not_的異常屬性 –

+0

@Mr_and_Mrs_D嘛,[它的工作(http://ideone.com/fyrrFv),所以爲什麼你認爲它不會是一個屬性? – phihag