所以我有一个程序来推理一个行文件并将任何错误输出到stderr。所以,如果我得到如下输入:
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
^
它只显示一行。那么如何才能打印出所有的线条呢?这是我的代码与try bock:
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)
答案 0 :(得分:0)
不确定这是否解决了问题,但在查看代码时会弹出两件事......
(1)except
块没有缩进try
块。
(2)因此,line_number
和offset
变量似乎永远不会更新。
如果您将except
块放在try
级别,则每次发现异常时都会执行except
下的代码,而您无需添加其中的第二个for line ...
循环。