pythonregexpython-3.xparsingg-code

Using re.compile function to parse a gcode file line by line in Python


I'm parsing a gcode file (located in f_path) line by line, searching for a given string. That string ("M622") appears a single text in the whole text file, whose structure is like this one:

GCODE FILE

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 

In the end, I want the code to return the line number where the string was found.

CODE

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)

As I run the code above, I enter in an infinite loop. Any suggestions?


Solution

  • you could do:

    import re
    rgx_start = re.compile(r'M622') 
    with open('gt.dat','r') as textfile:
       for i,line in enumerate(textfile.readlines()):
           if  rgx_start.search(line):
               line = i
               break  # since you said that it appears once
    print(line)