蟒蛇"AttributeError: 'NoneType' object has no attribute"错误



我正试图编写一个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
....

感谢您的帮助

祝大家都有美好的一天

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

您的代码正在寻找以'G00'或'G01'开头的第一行,在这种情况下将是行:"G00 E0;没有extrusion"然后试着找出字母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的回答来理解原因。

相关内容

最新更新