私は、ラインファイルを推測し、エラーを標準エラー出力に出力するプログラムを持っています。だから私はこのようになります入力取得する場合:Python - エラーを出力する
line 1 2x 3 4
line 1 2 x3 4
lixe 251 2 3 4 5
line 1 2 3 4
line 251 2 3 4
を次に出力は次のようになります。
Error in line 1:
line 1 2x 3 4
^
Error in line 2:
line 1 2 x3 4
^
Error in line 3:
lixe 251 2 3 4 5
^
Error in line 5:
line 251 2 3 4
^
Error in line 6:
line 1 2 3 4 5
^
だからここに私は、エラーチェックのために持っているものだ:
except Exception as e:
for line in lines_file:
print >> sys.stderr, 'Error in line ' + str(line_number) + ":"
print >> sys.stderr, " " * 4 + line,
print >> sys.stderr, " " * (offset + 4) + "^"
sys.exit(1)
しかし、このためにコードは、出力は次のようになります:
Error in line 1:
line 1 2 x3 4
^
Error in line 1:
lixe 251 2 3 4 5
^
Error in line 1:
line 1 2 3 4
^
Error in line 1:
line 251 2 3 4
^
Error in line 1:
line 1 2 3 4 5
^
Error in line 1:
line 1 2 3 4 x5
^
それは1行だけを表示します。では、どうすればすべての行を印刷することができますか?ここでトライボックと私のコードは次のとおりです。これで問題が解決するが、あなたのコードを見ているときに、2つのものが飛び出している場合で字下げないで
が(1)except
ブロック...
for line in lines_file:
line_number = 1
#get offset up to start of coordinates
start = re.compile('\s*line\s*')
m = start.match(line)
offset = m.end()
try:
for i in range(4):
xy = re.compile('\s*([-]?[0-9]{1,3})\s*')
if xy.match(line,offset):
m = xy.match(line,offset)
else:
raise Exception
coordinate = m.group(1)
if int(coordinate) > 250 or int(coordinate) < -250:
raise Exception
offset = m.end()
end = re.compile('\s*$')
if not end.match(line,offset):
raise Exception
except Exception as e:
for line in lines_file:
print >> sys.stderr, 'Error in line ' + str(line_number) + ":"
print >> sys.stderr, " " * 4 + line,
print >> sys.stderr, " " * (offset + 4) + "^"
sys.exit(1)
line_number += 1
offset = 0
p = re.compile('line\s*([-]?[0-9]{1,3})\s*([-]?[0-9]{1,3})\s*([-]?[0-9]{1,3})\s*([-]?[0-9]{1,3})')
m = p.match(line)
x0 = int(m.group(1))
y0 = int(m.group(2))
x1 = int(m.group(3))
y1 = int(m.group(4))
print str(x0), str(y0), str(x1), str(y1)
すべてを印刷するループを作成する必要があります – ABC
どのようなループの種類。それはあなたが "xの行"のところに行く各ループのためですか? – Chase
私のプログラムをさらに表示するようにコードを更新しました。 – Chase