我正在逐行解析一个 gcode 文件(位于 f_path 中),搜索给定的字符串。该字符串(“M622”)在整个文本文件中出现一个文本,其结构如下:
代码文件
M622; arm the Lasers
M610 S0 A80 B0 C0 ; allocate feeders
T0 ; set active extruder
G92 E0 ; set active extruder to 0
G28 XY ; home X and Y
G28 X ; home x
G90 ; absolute
G0 F3000 X35 Y5 S255 ; edge of plate
G92 X0 Y0 Z-2 ; local home
G0 Z0 ; drop Z
最后,我希望代码返回找到字符串的行号。
代码
rgx_start = re.compile(r'M622') # String to be searched: "M622"
with open (f_path, 'rt') as txtfile:
line = txtfile.readline()
line_i = 0 # Counter of each line in the original text file
hdr_start = 0 # Variable to store the line number where the header starts
while line: # Reading each line as a string
while rgx_start.search(line) != None: # No "M622" is found => move to the next line
line_i += 1 # The line counter is set to the next line
hdr_start = line_i # When "M622" is found
print('First line: ',hdr_start)
当我运行上面的代码时,我进入了一个无限循环。有什么建议么?