繁体   English   中英

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

[英]Python - Attribute error, 'NoneType' object has no attribute

因此,我有一个程序,该程序可以推理出行文件并向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()但我似乎无法弄清楚为什么这会导致错误。

如果找不到匹配项,则re.match返回None。 在这种情况下,您需要检查if m is None

您的代码中有两行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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM