Python - 属性错误,' NoneType'对象没有属性

时间:2016-03-27 06:55:11

标签: python

所以我有一个程序来推理一个行文件并将任何错误输出到stderr。

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(),但我似乎无法弄清楚导致错误的原因。

2 个答案:

答案 0 :(得分:0)

找不到匹配项时,

re.match返回None。对于这种情况,您需要检查if m is None

答案 1 :(得分:0)

代码中有两行offset = m.end()。问题必须在这里:

m = start.match(line)
offset = m.end()

因为另一行位于try - except块中。

您可以将其更改为:

m = start.match(line)
if m is not None:
    offset = m.end()

如果没有匹配则保留旧偏移量,即mNone