当前位置: 动力学知识库 > 问答 > 编程问答 >

Python - printing out errors

问题描述:

So I have a program that reason a lines file and prints out any errors to stderr. So if I get input that looks like this:

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

Then the output should look like:

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

^

So here's what I have for error checking:

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)

But for this code, the output looks like this:

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

^

And it only shows the one line. So how can I make it print out all the lines? Here's my code with the 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)

网友答案:

Not sure if this solves the problem, but two things pop out when looking at your code...

(1) The except block in not indented with the try block.

(2) As a consequence, the line_number and offset variables never seem to be updated.

If you put the except block at the level of try, then the code under except would be executed every time you find an exception, and you would not need to add a second for line ... loop within it.

分享给朋友:
您可能感兴趣的文章:
随机阅读: