簡體   English   中英

Python“AttributeError:'NoneType'對象沒有屬性”錯誤

[英]Python "AttributeError: 'NoneType' object has no attribute" Error

我正在嘗試編寫一個 Python 代碼來從“inkscape”gcode 文件中提取坐標,並將這些坐標用作另一個函數的輸入。 就像我是編程和 Python 的初學者一樣。 我寫了很簡單的幾行,你可以在下面看到。 當我嘗試運行代碼時,我收到“AttributeError: 'NoneType' object has no attribute 'start'”錯誤。 我認為這是關於循環“xindex.start()”返回空值的乞求,所以我想我需要定義一個初始值,但我找不到如何去做。 示例代碼僅適用於 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;無擠壓” ,然后它試圖找到字母 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 的回答以了解原因。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM