所以我有一個程序會導致一個行文件並將任何錯誤打印到stderr。所以,如果我得到的輸入,看起來像這樣: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
^
它只顯示一行。那麼我怎麼才能讓它打印出所有的行呢?這裏是我與嘗試博克代碼:
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
什麼樣的循環。對於每個循環,你是否「爲了排隊」? – Chase
好的,我更新了我的代碼以顯示更多我的程序。 – Chase