Python“AttributeError:'NoneType'对象没有属性”错误

2024-06-28 10:59:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图编写一个Python代码,从“inkscape”gcode文件中提取坐标,并将这些坐标作为另一个函数的输入。我是编程和Python的初学者。我写了几行非常简单的文字,你可以在下面看到。当我尝试运行代码时,我得到了“AttributeError:'NoneType'对象没有属性'start'”错误。我想这是关于循环“xindex.start()”返回null的乞讨,所以我想我需要定义一个初始值,但我找不到如何做。示例代码仅适用于X值

import re
  with open("example.gcode", "r") as file:
       for line in file:
        if line.startswith('G00') or line.startswith('G01'): # find the lines which start with G00 and G01
         xindex = re.search("[X]", line) # search for X term in the lines
         xindex_number = int(xindex.start()) # find starting index number and convert it to int

gcode的内部看起来像:

S1; endstops
G00 E0; no extrusion
G01 S1; endstops
G01 E0; no extrusion
G21; millimeters
G90; absolute
G28 X; home
G28 Y; home
G28 Z; home
G00 F300.0 Z20.000; pen park !!Zpark
G00 F2400.0 Y0.000; !!Ybottom
....

谢谢你的帮助

祝大家有一个愉快的一天


Tags: 代码inrehomeforwithlinestart
2条回答

AttributeError: 'NoneType' object has no attribute 'start'表示您试图对一个等于零的对象调用.start()

代码正在查找以“G00”或“G01”开头的第一行,在本例中,这将是一行:“G00 E0;无拉伸”,然后它尝试查找该行中字母X的位置

在本例中,该行中不存在“X”,因此xindex = None。因此,调用xindex.start()时不能不抛出错误。这就是错误告诉你的

添加一个if条件,它应该可以正常工作

import re
with open("example.gcode", "r") as file:
    for line in file:
        if line.startswith("G00") or line.startswith("G01"):
            xindex = re.search("[X]", line)

            # Check if a match was found
            if xindex:
                xindex_number = int(xindex.start())

并参考@QuantumMecha 's answer了解原因

相关问题 更多 >