2016-10-14 1 views
0

データベースのデータテーブルからデータを読み込んでいます。このメソッドは、データベース内のテーブルにデータがない場合に例外をスローします。データベースからの読み込み時にpythonスクリプトでエラーが発生しました。

def readData(table): 
"""Read the database table, parse it according to the field map, and return list of parsed lines""" 
cmd = GETTABLE + ' ' + table 
records = [] 
try: 
    result = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE) 
    data = result.communicate()[0] 
except subprocess.CalledProcessError, e: 
    errorExit('Unable to read ' + table + ': ' + str(e)) 
if (result.returncode > 0): 
    errorExit('Unable to read ' + table + ': ' + data) 

lines = data.split('\n') 
# Get rid of all the blank lines 
lines = [line for line in lines if len(line)>0] 
# Pop the first line of the data and use it to parse the column names into a map 
header = lines.pop(0) 
fieldmap = createFieldMap(header) 

for line in lines: 
    records.append(getFieldMap(line, fieldmap)) 
return records 

テーブル内のデータがないので、エラーがラインheader = lines.pop(0)でスローされます。

空のデータ処理をここで正常に処理する方法を教えてください。

次のエラーがこのスクリプトの実行に見られている:

Traceback (most recent call last): File "./dumpLineSegments", line 204, in gnrMemberMap, gnrGroupMap = getGenericMemberMap('PPWR_GNR_MEM') File "./dumpLineSegments", line 119, in getGenericMemberMap for gnrMember in readData(tablename): File "./dumpLineSegments", line 78, in readData header = lines.pop(0) IndexError: pop from empty list

+2

'if len(lines)== 0:... ' – smarx

+0

コードを正しくインデントして、例外テキスト(私が推測するIndexError)を含めることができますか? pop&IndexErrorを見ている人はあなたの質問を見つけるでしょう。 – oekopez

答えて

0

まず、私は、インデントが保存されるような方法でコードを編集して、エラーメッセージが表示されるでしょう。与えられたsmarxによるコメントのように、あなたが何かをポップするために残っているかどうかを確認する必要があります。しかし、次の行もエラーが発生しやすく、問題を処理する必要があります。例えば。行はそこにありますが、それが正式なヘッダーではない場合、これは警告を出します(私の例では)。しかし、意味のある例外を発生させることも良い考えです。 空白以外の空白行を確認することもお勧めします。コードの2番目の部分は、次に示します:

lines = data.split('\n') 
# Get rid of all the blank lines, stripping whitespace. Test for 
# an empty string can be done as if line 
lines = [line.strip() for line in lines if line.strip()] 
# Pop the first line of the data and use it to parse the column names into a map 
if lines: # check if you have any lines 
    header = lines.pop(0) 
    try: # I guess you parse the header somehow, which can fail 
     fieldmap = createFieldMap(header) 
    except FieldmapError: # or whatever error is raised when the parsing of the header fails 
     warning.warn('{} is not a valid header'.format(header)) 
     return None 
    else: 
     for line in lines: 
      records.append(getFieldMap(line, fieldmap)) 
     return records 
else: 
    return None 

あなたはデータがない場合は警告が発生し、誤ったヘッダの場合には、どれも黙って、返されません。 しかし、可能であれば私はシステムコールの代わりにpythonデータベースドライバを使ってデータベースに問い合わせます。

+0

2行目のコードには、 '' line.stip() ''があります。 – Schmuddi

+0

返信ありがとうございますが、ラインlines.pop(0)でエラーが発生しています。 FieldMapを作成する前にtryを配置すると、FieldMapErrorに関するエラーのみが処理されますが、lines.pop(0)にエラーがスローされます。 – Scientist

+0

エラーの解決方法は「if lines:」です。 – oekopez