2017-11-05 5 views
1

Pythonでより具体的なエラーメッセージを表示する方法はありますか?例えば、完全なエラーコードやエラーが、見つけることができない正確なファイルではなく、一般的な"The system cannot find the file specified")Pythonで正確なエラーメッセージを出力する

for file in ['C:/AA/HA.csv', 'C:/AA1/HA1.csv']: 
     try: 
      os.remove(file) 
     except OSError as e: 
      pass 
      print(getattr(e, 'message', repr(e))) 
      #print(getattr(e, 'message', repr(e))) 
      #print(e.message) 
      #print('File Not Removed') 

次のプリント二回に発生し、少なくとも行:これは素晴らしいですが

FileNotFoundError(2, 'The system cannot find the file specified') 

をバグ修正のためのより正確なエラーメッセージを得る方法はありますか?

次は、ジョブを停止しますが、コンソールでexact line being 855を配るだけでなく、ファイルdirectory ''C:/AC/HA.csv''.

os.remove('C:/AA/HA.csv') 
Traceback (most recent call last): 
    File "C:/ACA.py", line 855, in <module> 
    os.remove('C:/AC/HA.csv') 
FileNotFoundError: [WinError 2] The system cannot find the file specified: ''C:/AC/HA.csv'' 

答えて

1

tracebackモジュールを参照してください:

import os 
import traceback 

for file in ['C:/AA/HA.csv', 'C:/AA1/HA1.csv']: 
    try: 
     os.remove(file) 
    except OSError as e: 
     traceback.print_exc() 

出力:

Traceback (most recent call last): 
    File "C:\test.py", line 6, in <module> 
    os.remove(file) 
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:/AA/HA.csv' 
Traceback (most recent call last): 
    File "C:\test.py", line 6, in <module> 
    os.remove(file) 
FileNotFoundError: [WinError 3] The system cannot find the path specified: 'C:/AA1/HA1.csv' 
関連する問題