Skip to content

Parsing gcode

Peter Boin edited this page Jul 28, 2017 · 2 revisions

Parsing gcode

To read gcode from a file, utilise the Line class. Each Line instance contains a Block and an optional Comment. The Block contains a list of gcodes you're after.

from pygcode import Line

with open('part.gcode', 'r') as fh:
    for line_text in fh.readlines():
        line = Line(line_text)

        print(line)  # will print the line (with cosmetic changes)
        line.block.gcodes  # is your list of gcodes
        line.block.modal_params  # are all parameters not assigned to a gcode, assumed to be motion modal parameters
        if line.comment:
            line.comment.text  # your comment text

To elaborate, here are some line examples

>>> from pygcode import Line

>>> line = Line('G01 x1 y2  f100 s1000 ; blah')
>>> print(line)
G01 X1 Y2 F100 S1000 ; blah

>>> print(line.block)
G01 X1 Y2 F100 S1000

>>> sorted(line.block.gcodes)
[<GCodeFeedRate: F100>,
 <GCodeSpindleSpeed: S1000>,
 <GCodeLinearMove: G01{X1, Y2}>]

>>> print(line.comment)
; blah
Clone this wiki locally