私は行ファイルを推論し、エラーを標準エラー出力に出力するプログラムを持っています。Python - 属性エラー、 'NoneType'オブジェクトには属性がありません
for line in lines_file:
#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:
print >> sys.stderr, 'Error in line ' + str(line_number) + ":"
print >> sys.stderr, " " * 4 + line,
print >> sys.stderr, " " * (offset + 4) + "^"
line_number = line_number + 1
continue
そして、私はstderrに出力する無効な行を期待して、無効な入力ラインに入れた場合、私が手出力は次のようになります。
Traceback (most recent call last):
File "lines_to_svg.py", line 37, in <module>
offset = m.end()
AttributeError: 'NoneType' object has no attribute 'end'
これは私のコードの断片であるので、37行されますoffset = m.end()
と書いてあります。だから、なぜ私は属性のエラーを取得し続けますか?ここで念のために、これはエラーの原因となっている上記のforループの前に来るコードは次のとおりです。
import sys
import re
# SVG header with placeholders for canvas width and height
SVG_HEADER = "<svg xmlns=\"http:#www.w3.org/2000/svg\" version=\"1.1\""" width=\"%d\" height=\"%d\">\n"
# SVG bounding box with placeholders for width and height
SVG_BOUNDING_BOX = "<rect x=\"0\" y=\"0\" width=\"%d\" height=\"%d\""" style=\"stroke:#000;fill:none\" />\n"
# SVG line with placeholders for x0, y0, x1, y1
SVG_LINE = "<line x1=\"%d\" y1=\"%d\" x2=\"%d\" y2=\"%d\""" style=\"stroke:#000\" />\n"
# SVG footer
SVG_FOOTER = "</svg>"
CANVAS_HEIGHT = 500
CANVAS_WIDTH = 500
# process command line arguments
if len(sys.argv) != 2:
print >> sys.stderr, "Usage:", str(sys.argv[0]), "lines_file"
exit(1)
#open file for reading
try:
lines_file = open(sys.argv[1], 'r')
except IOError:
print >> sys.stderr, "Cannot open:", str(sys.argv[1])
exit(2)
offset = 0
line_number = 1
問題がoffset = m.end()
であるが、私はそれがエラーの原因である理由を見つけ出すように見えることはできません。
実際に実行したコードが表示されていないように見えます。 'offset = m.end()'の行は 'try'-' except'ブロックの中にあります。したがって、デフォルトのトレースバックではなく、エラーハンドラの出力が必要です。 –
私は完全な出力を表示していません。私の出力の最初の2行は、無効な行のエラーを表示しますが、その後は属性エラーを示します。 – Chase
トレースバックを読み取ります。それを解釈する唯一の方法があります。あなたはまだトレースバックを読む方法を学んだことがありますか? –