### Install gcodeparser from Git Source: https://github.com/andyeveritt/gcodeparser/blob/master/README.md Alternative installation method: install directly from the GitHub repository master branch using pip. ```bash pip install -e "git+https://github.com/AndyEveritt/GcodeParser.git@master#egg=gcodeparser" ``` -------------------------------- ### Install gcodeparser via pip Source: https://github.com/andyeveritt/gcodeparser/blob/master/README.md Install the gcodeparser package from PyPI using pip. ```bash pip install gcodeparser ``` -------------------------------- ### Parameters output for line 5 Source: https://github.com/andyeveritt/gcodeparser/blob/master/main.ipynb Example output of parsed_gcode.lines[5].params showing the parameter dictionary. ```text Result: {'Y': 88.675, 'F': 9000.0} ``` -------------------------------- ### Regex parsing output Source: https://github.com/andyeveritt/gcodeparser/blob/master/main.ipynb Example output of the regex parsing loop, showing tuples of matches and extracted parameters. ```text Output: ('', '', '', '', '', '', '', '', 'Networking') ('M', '552', ' P0.0.0.0 S1', ' S1', '1', '1', '', '', '') ('M', '550', ' P"ForceRig; "', ' P"ForceRig; "', '"ForceRig; "', '', '', '', '') ('', '', '', '', '', '', '', '', 'General preferences') ('G', '21', '', '', '', '', '', '', '') ('G', '1', ' X10', ' X10', '10', '10', '', '', '') ('G', '1', ' Z-0.500 F600', ' F600', '600', '600', '', '', '') ('G', '1', ' X150.780 Y88.675 F9000', ' F9000', '9000', '9000', '', '', '') ('G', '1', ' Z0.200 F600', ' F600', '600', '600', '', '', '') ('G', '1', ' E0.8000 F6000', ' F6000', '6000', '6000', '', '', '') ('G', '1', ' X152.506 Y88.828 E0.0692 F2400', ' F2400', '2400', '2400', '', '', '') ('G', '1', ' X152.642 Y88.846 E0.0055', ' E0.0055', '0.0055', '0.0055', '', '', '') ('M', '116', '', '', '', '', '; wait for temps to settle', 'wait for temps to settle', '') ('T', '0', '', '', '', '', '', '', '') ``` -------------------------------- ### Usage examples for gcode_str Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-line.md Shows how to construct GcodeLine objects and print their gcode_str output. Demonstrates normal parameters, flag parameters, and comment-only lines. ```python from gcodeparser import GcodeLine line = GcodeLine(command=("G", 91), params={"X": 10, "Y": 20}, comment="this is a comment", line_index=0) print(line.gcode_str) # "G91 X10 Y20 ; this is a comment" flag = GcodeLine(command=("G", 28), params={"X": True}, comment="", line_index=0) print(flag.gcode_str) # "G28 X" comment_only = GcodeLine(command=(";", None), params={}, comment="hello", line_index=0) print(comment_only.gcode_str) # "; hello" ``` -------------------------------- ### Parsed G-code lines output Source: https://github.com/andyeveritt/gcodeparser/blob/master/main.ipynb Example output of parsed_gcode.lines[0:14] showing GcodeLine objects with command tuples, parameter dictionaries, and comments. ```text Result: [GcodeLine(command=('M', 552), params={'P': '01.0.0.0', 'S': 1}, comment=''), GcodeLine(command=('M', 550), params={'P': '"ForceRig; "'}, comment=''), GcodeLine(command=('G', 21), params={'P': 0}, comment=''), GcodeLine(command=('G', 1), params={'X': 10}, comment=''), GcodeLine(command=('G', 1), params={'Z': -0.5, 'F': 600.0}, comment=''), GcodeLine(command=('G', 1), params={'X': 150.78, 'Y': 88.675, 'F': 9000.0}, comment=''), GcodeLine(command=('G', 1), params={'Z': 0.2, 'F': 600.0}, comment=''), GcodeLine(command=('G', 1), params={'E': 0.8, 'F': 6000.0}, comment=''), GcodeLine(command=('G', 1), params={'X': 152.506, 'Y': 88.828, 'E': 0.0692, 'F': 2400.0}, comment=''), GcodeLine(command=('G', 1), params={'X': 152.642, 'Y': 88.846, 'E': 0.0055}, comment=''), GcodeLine(command=('M', 116), params={}, comment='wait for temps to settle'), GcodeLine(command=('T', 0), params={}, comment=''), GcodeLine(command=('G', 90), params={}, comment=''), GcodeLine(command=('M', 83), params={}, comment='')] ``` -------------------------------- ### Basic parsing examples Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/parse-parameters.md Shows various inputs to parse_parameters and their expected outputs, including numeric, quoted string, flag, and IP-address-like values. ```python from gcodeparser import parse_parameters parse_parameters(" P0 S1 X10") # {'P': 0, 'S': 1, 'X': 10} parse_parameters(" P0.1 S1.1345 X10.0") # {'P': 0.1, 'S': 1.1345, 'X': 10.0} parse_parameters(' P"string ; semicolon"') # {'P': '"string ; semicolon"'} parse_parameters(" P-0 S-1 X-10") # {'P': 0, 'S': -1, 'X': -10} parse_parameters("P192.168.0.1 S1") # {'P': '192.168.0.1', 'S': 1} parse_parameters(" X") # {'X': True} parse_parameters("P0.1S1.1345X10.0A\"string\"") # {'P': 0.1, 'S': 1.1345, 'X': 10.0, 'A': '"string"'} ``` -------------------------------- ### Import GcodeParser and GcodeLine Source: https://github.com/andyeveritt/gcodeparser/blob/master/main.ipynb Import the main classes from the gcodeparser library. ```python from gcodeparser import GcodeParser, GcodeLine ``` -------------------------------- ### Example Output of parse_gcode_lines Source: https://github.com/andyeveritt/gcodeparser/blob/master/README.md Sample output showing a list of GcodeLine objects with command, params, and comment fields. The output is truncated with '...'. ```python [GcodeLine(command=('G', 10), params={'P': 0, 'R': 0, 'S': 0}, comment='sets the standby temperature'), GcodeLine(command=('G', 29), params={'S': 1}, comment=''), GcodeLine(command=('T', 0), params={}, comment=''), GcodeLine(command=('G', 21), params={}, comment='set units to millimeters'), GcodeLine(command=('G', 90), params={}, comment='use absolute coordinates'), GcodeLine(command=('M', 83), params={}, comment='use relative distances for extrusion'), GcodeLine(command=('G', 1), params={'E': -0.6, 'F': 3600.0}, comment=''), GcodeLine(command=('G', 1), params={'Z': 0.45, 'F': 7800.0}, comment=''), GcodeLine(command=('G', 1), params={'Z': 2.35}, comment=''), GcodeLine(command=('G', 1), params={'X': 119.575, 'Y': 89.986}, comment=''), GcodeLine(command=('G', 1), params={'Z': 0.45}, comment=''), GcodeLine(command=('G', 1), params={'E': 0.6, 'F': 3600.0}, comment=''), GcodeLine(command=('G', 1), params={'F': 1800.0}, comment=''), GcodeLine(command=('G', 1), params={'X': 120.774, 'Y': 88.783, 'E': 0.17459}, comment=''), GcodeLine(command=('G', 1), params={'X': 121.692, 'Y': 88.145, 'E': 0.11492}, comment=''), GcodeLine(command=('G', 1), params={'X': 122.7, 'Y': 87.638, 'E': 0.11596}, comment=''), GcodeLine(command=('G', 1), params={'X': 123.742, 'Y': 87.285, 'E': 0.11317}, comment=''), ... ] ``` -------------------------------- ### update_param usage example Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-line.md Example of using update_param. It returns the updated value via get_param, or None if the parameter does not exist. Passing a non-int/float value raises TypeError. ```python from gcodeparser import GcodeLine line = GcodeLine(command=("G", 1), params={"X": 10}, comment="", line_index=0) line.update_param("X", 42) # returns 42, line.params == {"X": 42} line.update_param("Y", 1) # returns None (param absent, dict unchanged) line.update_param("X", "hi") # raises TypeError ``` -------------------------------- ### Parse a G-code file and inspect first lines Source: https://github.com/andyeveritt/gcodeparser/blob/master/main.ipynb Reads a G-code file and parses it with GcodeParser. The parsed lines are stored in parsed_gcode.lines; the example shows the first 14 lines. ```python with open('3DBenchy.gcode', 'r') as f: gcode = f.read() parsed_gcode = GcodeParser(gcode) parsed_gcode.lines[0:14] ``` -------------------------------- ### Include Comments Example Source: https://github.com/andyeveritt/gcodeparser/blob/master/README.md Shows how to include comment-only lines by setting include_comments=True. The gcode string contains a comment line that will be included in the output. ```python from gcodeparser import parse_gcode_lines gcode = """G1 X1 ; this comment is always included ; this comment will only be included if `include_comments=True`""" lines = list(parse_gcode_lines(gcode, include_comments=True)) ``` -------------------------------- ### Usage Examples for parse_gcode_lines Source: https://github.com/andyeveritt/gcodeparser/blob/master/README.md Shows three ways to use parse_gcode_lines: iterating over a file, converting to a list, and parsing a string. The file must be open during iteration. include_comments=False is used to exclude comment-only lines. ```python from gcodeparser import parse_gcode_lines # Recommended: iterate over lines in a file with open('my_gcode.gcode', 'r') as f: # note that file should be open during iteration for line in parse_gcode_lines(f, include_comments=False): print(line) # Alternative: open gcode file and parse lines into a list without iteration with open('my_gcode.gcode', 'r') as f: lines = list(parse_gcode_lines(f, include_comments=False)) # Also, we can convert string to parsed lines with open('my_gcode.gcode', 'r') as f: gcode = f.read() lines = list(parse_gcode_lines(gcode, include_comments=False)) ``` -------------------------------- ### Convert to Pandas DataFrame Source: https://github.com/andyeveritt/gcodeparser/blob/master/README.md Shows how to convert a list of GcodeLine objects into a pandas DataFrame. Requires pandas to be installed. ```python from gcodeparser import parse_gcode_lines import pandas as pd with open('my_gcode.gcode', 'r') as f: lines = list(parse_gcode_lines(f)) df = pd.DataFrame(lines) ``` -------------------------------- ### delete_param usage example Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-line.md Example of using delete_param. It removes the specified parameter from the params dictionary. If the parameter is absent, it is a no-op. ```python from gcodeparser import GcodeLine line = GcodeLine(command=("G", 1), params={"X": 10, "Y": 20}, comment="", line_index=0) line.delete_param("X") # params == {"Y": 20} line.delete_param("Z") # no-op, params unchanged ``` -------------------------------- ### Access parameters of a specific line Source: https://github.com/andyeveritt/gcodeparser/blob/master/main.ipynb Shows how to access the params dictionary of a specific parsed line (index 5). ```python parsed_gcode.lines[5].params ``` -------------------------------- ### Basic inference examples Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/infer-element-type.md Demonstrates how infer_element_type classifies various input strings, including integers, floats, and strings with quotes or two dots. ```python from gcodeparser import infer_element_type infer_element_type("109321") # int infer_element_type("-109321") # int infer_element_type("109321.0") # float infer_element_type("-1.013456") # float infer_element_type(".0001") # float infer_element_type("192.168.0.1") # str (two dots) infer_element_type('"test string"') # str (quoted) ``` -------------------------------- ### GcodeLine Object Structure Example Source: https://github.com/andyeveritt/gcodeparser/blob/master/README.md Shows the structure of a GcodeLine object parsed from a gcode line like 'G1 X10 Y-2.5 ; this is a comment'. The command is a tuple, params is a dict, comment is a string, line_index is an integer, and type is one of the Commands enum values. ```python GcodeLine( command = ('G', 1), params = {'X': 10, 'Y': -2.5}, comment = 'this is a comment', line_index = 0, type = Commands.MOVE # Commands.MOVE, Commands.COMMENT, Commands.OTHER, Commands.TOOLCHANGE ) ``` -------------------------------- ### Regex-based G-code parsing with re.findall Source: https://github.com/andyeveritt/gcodeparser/blob/master/main.ipynb Uses a regular expression to parse G-code lines and prints the first 14 matches along with extracted parameters. The regex is defined and then applied to the gcode string. ```python import re regex = r'(?!; *.+)(G|M|T|g|m|t)(\d+)(( *(?!G|M|g|m)\w(((-?\d+\.?)*)|".*"))*) *\t*(; *(.*))?|; *(.+)' regex = r'(?!; *.+)(G|M|T|g|m|t)(\d+)(( *(?!G|M|g|m)\w(".*"|([-\d\.]*)))*) *\t*(; *(.*))?|; *(.+)' # regex = r'(?!; *.+)(G|M|T|g|m|t)(\d+)( *(?!G|M|g|m)[^;\n]*) *\t*(; *\t*(.*))?|; *(.+)' regex_lines = re.findall(regex, gcode) for line in regex_lines[0:14]: print(line) print(re.findall(r'((?!\d)\w+?)(".*"|(\d+\.?)+|-?\d+\.?\d*)', line[2])) ``` -------------------------------- ### GcodeLine get_param usage examples Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-line.md Shows typical calls: type casting truncates floats with `int`, stringifies with `str`, and returns `default` when the key is absent. ```python from gcodeparser import GcodeLine line = GcodeLine(command=("G", 1), params={"X": 10.5, "S": "200"}, comment="", line_index=0) line.get_param("X") # 10.5 line.get_param("X", return_type=int) # 10 (truncated) line.get_param("X", return_type=str) # "10.5" line.get_param("S", return_type=float) # 200.0 line.get_param("Y") # None line.get_param("Y", default=0) # 0 ``` -------------------------------- ### command_str (property) Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-line.md Returns the command tuple flattened to a string. For example, ('G', 91) becomes "G91" and (';', None) becomes ";". ```APIDOC ## command_str (property) ### Description Returns the command tuple flattened to a string. For example, ('G', 91) becomes "G91" and (';', None) becomes ";". ### Method command_str (property) ### Parameters None ### Return Value - `str` - The command tuple flattened to a string. ### Example ```python from gcodeparser import GcodeLine line = GcodeLine(command=("G", 91), params={"X": 10}, comment="", line_index=0) print(line.command_str) # "G91" ``` ``` -------------------------------- ### __post_init__ (type computation) Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-line.md Automatically computes the `type` field based on the command tuple. This is called during initialization and is not intended to be called directly by users. ```APIDOC ## __post_init__ (type computation) ### Description Automatically computes the `type` field based on the command tuple. This is called during initialization and is not intended to be called directly by users. ### Method __post_init__ ### Parameters None ### Return Value None (sets `self.type`) ### Behavior - If command letter is 'G' and number in (0, 1, 2, 3), type is `Commands.MOVE` - If command letter is ';', type is `Commands.COMMENT` - If command letter is 'T', type is `Commands.TOOLCHANGE` - Otherwise, type is `Commands.OTHER` ``` -------------------------------- ### Basic: iterate over a file (recommended) Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/parse-gcode-lines.md Recommended usage: open a G-code file and iterate over parsed lines. The file must remain open during iteration because the generator streams line-by-line. Prints command and params for each line. ```python from gcodeparser import parse_gcode_lines with open('my_gcode.gcode', 'r') as f: # file must stay open during iteration for line in parse_gcode_lines(f, include_comments=False): print(line.command, line.params) ``` -------------------------------- ### Basic: parse a string with output Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/parse-gcode-lines.md Parses a G-code string into a list of GcodeLine objects and prints command, params, comment, and line_index for each. The displayed output shows the expected results for the given input. ```python from gcodeparser import parse_gcode_lines gcode = "G1 X10 Y-2.5 ; this is a comment\nT0\nM104 S200" lines = list(parse_gcode_lines(gcode)) for line in lines: print(line.command, line.params, line.comment, line.line_index) ``` ```text ('G', 1) {'X': 10, 'Y': -2.5} 'this is a comment' 0 ('T', 0) {} '' 1 ('M', 104) {'S': 200} '' 2 ``` -------------------------------- ### Serializing with the value Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/commands.md Shows that Commands values are stable integers and supports reverse lookup by value. ```python from gcodeparser import Commands # Values are stable integers: assert Commands.MOVE.value == 1 assert Commands(1) is Commands.MOVE # reverse lookup by value ``` -------------------------------- ### Catching TypeError from update_param Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/errors.md Example of catching the TypeError raised by update_param when passing a string value. The output shows the caught message: "Type is not a valid parameter type". ```python from gcodeparser import GcodeLine, parse_gcode_lines line = next(parse_gcode_lines("G1 X10 Y20")) try: line.update_param("X", "not-a-number") except TypeError as e: print(f"caught: {e}") # "Type is not a valid parameter type" else: print("updated") ``` -------------------------------- ### Parsing the parameter portion of a full command line Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/parse-parameters.md Demonstrates how to extract and parse the parameter substring from a full G-code command line by stripping the command word. ```python import re from gcodeparser import parse_parameters command_line = "G1 X10 Y-2.5 E0.17459 F1800.0" # strip the command word, take the rest params_text = command_line.split(None, 1)[1] params = parse_parameters(params_text) print(params) # {'X': 10, 'Y': -2.5, 'E': 0.17459, 'F': 1800.0} ``` -------------------------------- ### Basic use of GcodeParser Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-parser.md Shows how to instantiate GcodeParser and iterate over parsed lines. The output demonstrates the parsed command and parameters for each line. ```python from gcodeparser import GcodeParser parser = GcodeParser("G21\nG1 X10 Y20 ; move\nM104 S200") for line in parser.lines: print(line.command, line.params) # ('G', 21) {} # ('G', 1) {'X': 10, 'Y': 20} # ('M', 104) {'S': 200} ``` -------------------------------- ### Update Param with update_param Source: https://github.com/andyeveritt/gcodeparser/blob/master/README.md Shows how to update a parameter value using the update_param method. If the param does not exist, it returns None; otherwise it returns the updated value. ```python line.update_param('X', 10) ``` -------------------------------- ### GcodeLine.gcode_str property Source: https://github.com/andyeveritt/gcodeparser/blob/master/README.md Returns the equivalent gcode string for the GcodeLine object. ```APIDOC ## GcodeLine.gcode_str property ### Description Returns the equivalent gcode string for the GcodeLine object. ### Returns A string containing the gcode representation. ### Example ```python line.gcode_str ``` ``` -------------------------------- ### Retrieve Param with get_param Source: https://github.com/andyeveritt/gcodeparser/blob/master/README.md Shows how to retrieve a parameter value using the get_param method. The method returns the value if it exists, otherwise the default value. If return_type is set, the value is type cast. ```python line.get_param('X') ``` -------------------------------- ### Delete Param with delete_param Source: https://github.com/andyeveritt/gcodeparser/blob/master/README.md Shows how to delete a parameter using the delete_param method. ```python line.delete_param('X') ``` -------------------------------- ### Using the result to convert values Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/infer-element-type.md Shows how to use the returned type to convert a raw string to the appropriate Python value. ```python from gcodeparser import infer_element_type raw = "-0.003213" value = infer_element_type(raw)(raw) print(value, type(value)) # -0.003213 ``` -------------------------------- ### Assigning type in GcodeLine.__post_init__ Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/commands.md Logic that assigns the Commands type based on the command letter and number. MOVE is checked first, then COMMENT, TOOLCHANGE, and finally OTHER. ```python if self.command[0] == "G" and self.command[1] in (0, 1, 2, 3): self.type = Commands.MOVE elif self.command[0] == ";": self.type = Commands.COMMENT elif self.command[0] == "T": self.type = Commands.TOOLCHANGE else: self.type = Commands.OTHER ``` -------------------------------- ### gcode_str Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-line.md Returns the equivalent G-code source string for a GcodeLine instance. Parameters render in dict insertion order with no space between name and value; flag parameters render as bare letters; comments are appended as '; '; comment-only lines render as just the comment text. ```APIDOC ## Property: `gcode_str` ### Description Returns the equivalent G-code source string for a GcodeLine instance. Parameters render in dict insertion order with no space between name and value; flag parameters (True) render as the bare letter (e.g. `X`); a comment, if present, is appended as `; `; comment-only lines (`command == ";"`) render as just the comment text. ### Return Type `str` ### Example ```python from gcodeparser import GcodeLine line = GcodeLine(command=("G", 91), params={"X": 10, "Y": 20}, comment="this is a comment", line_index=0) print(line.gcode_str) # "G91 X10 Y20 ; this is a comment" flag = GcodeLine(command=("G", 28), params={"X": True}, comment="", line_index=0) print(flag.gcode_str) # "G28 X" comment_only = GcodeLine(command=(";", None), params={}, comment="hello", line_index=0) print(comment_only.gcode_str) # "; hello" ``` ### Notes Renamed from `to_gcode()` in versions ≤ `0.0.6`. ``` -------------------------------- ### Switching on the type Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/commands.md Iterates over parsed lines and uses the Commands type to print move or other commands. ```python from gcodeparser import Commands, parse_gcode_lines for line in parse_gcode_lines("G0 X1 Y2\nM104 S200"): if line.type is Commands.MOVE: print(f"move: {line.command_str}") elif line.type is Commands.OTHER: print(f"other: {line.command_str}") ``` -------------------------------- ### parse_gcode_lines(gcode, include_comments=False) Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/parse-gcode-lines.md The primary entry point of the gcodeparser library. Parses G-code from a string, StringIO, or open text file and yields GcodeLine objects one at a time as a generator (lazy, streaming). ```APIDOC ## parse_gcode_lines(gcode, include_comments=False) ### Description Parses G-code from a string, a `StringIO`, or an open text file and **yields** `GcodeLine` objects one at a time as a generator (lazy, streaming). This is the primary, recommended entry point of the library. ### Signature ```python def parse_gcode_lines(gcode: io.TextIOBase | io.StringIO | str, include_comments: bool = False) -> Iterator[GcodeLine]: ``` ### Parameters - **gcode** (`io.TextIOBase | io.StringIO | str`) - Required - The G-code content. A `str` is wrapped in `io.StringIO` internally. File-like objects are iterated line-by-line and **must remain open while iterating** the returned generator. - **include_comments** (`bool`) - Optional (default: `False`) - When `True`, lines that contain **only** a comment are emitted as `GcodeLine(command=(';', None), params={}, ...)`. When `False`, comment-only lines are skipped. Inline comments on command lines are always attached to the last command of the line regardless of this flag. ### Return Value An `Iterator[GcodeLine]` (a generator). Each yielded `GcodeLine` has: - `command` — `('G'|'M'|'T', int)` for commands, or `(';', None)` for comment-only lines - `params` — parsed parameter dict, keys uppercased - `comment` — the comment text without the leading `;` - `line_index` — zero-based index of the **physical source line** (multiple commands on one physical line share the same `line_index`) Lines that match neither a command nor a comment are silently skipped. ### Behavior Notes - Commands are matched by `GCODE_LINE_PATTERN`; the command letter is uppercased via `groups[0].upper()` and the number via `int(groups[1])`. - Multiple commands on one physical line (e.g. `G91 G1 X10 Y20`) produce one `GcodeLine` per command. - G-code-like text inside a comment is **not** parsed as a command. - The comment is taken from the inline-comment capture group of the last command match; if the comment-only match appears after the last command, its text is used. - Comment-only lines are only emitted when `include_comments=True`. ### Throws / Raises No custom exceptions are declared. Underlying `int(...)`/type conversions can raise built-in `ValueError`/`TypeError` if malformed input reaches the regex captures, but the pattern is designed to only match numeric command numbers and valid parameter tokens. Lines that do not match are skipped silently, not raised. ### Examples #### Basic: iterate over a file (recommended) ```python from gcodeparser import parse_gcode_lines with open('my_gcode.gcode', 'r') as f: # file must stay open during iteration for line in parse_gcode_lines(f, include_comments=False): print(line.command, line.params) ``` #### Basic: parse a string ```python from gcodeparser import parse_gcode_lines gcode = "G1 X10 Y-2.5 ; this is a comment\nT0\nM104 S200" lines = list(parse_gcode_lines(gcode)) for line in lines: print(line.command, line.params, line.comment, line.line_index) ``` Output: ``` ('G', 1) {'X': 10, 'Y': -2.5} 'this is a comment' 0 ('T', 0) {} '' 1 ('M', 104) {'S': 200} '' 2 ``` #### include_comments option ```python from gcodeparser import parse_gcode_lines gcode = """G1 X1 ; this comment is always included ; this comment needs include_comments=True""" lines = list(parse_gcode_lines(gcode, include_comments=True)) # lines[1].command == (';', None) # lines[1].comment == "this comment needs include_comments=True" without = list(parse_gcode_lines(gcode, include_comments=False)) # without has only 1 element: the G1 command ``` #### Multiple commands per line ```python from gcodeparser import parse_gcode_lines lines = list(parse_gcode_lines("G91 G1 X10 Y20 ; inline comment")) # 2 elements, both with line_index == 0 assert lines[0].command == ("G", 91) assert lines[1].command == ("G", 1) assert lines[1].comment == "inline comment" # attached to the LAST command ``` #### Streaming with early exit Because the function is a generator, you can stop consuming at any time without reading the whole input: ```python from gcodeparser import parse_gcode_lines with open('big.gcode', 'r') as f: for i, line in enumerate(parse_gcode_lines(f)): if line.command[0] == 'T': # tool change print(f"tool change on line {line.line_index}") break ``` ### Related - [GcodeLine](gcode-line.md) — the yielded object type - [parse_parameters](parse-parameters.md) — parameter tokenization used internally - [GcodeParser](gcode-parser.md) — deprecated non-streaming alternative ``` -------------------------------- ### GcodeParser.__init__ Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-parser.md Constructs a GcodeParser instance. This class is deprecated since 0.3.0 and emits a DeprecationWarning; use parse_gcode_lines instead. ```APIDOC ## GcodeParser.__init__ ### Description Constructs a GcodeParser instance. This class is deprecated since 0.3.0 and emits a DeprecationWarning; use parse_gcode_lines instead. ### Method Constructor ### Endpoint GcodeParser(gcode: str, include_comments: bool = False) ### Parameters #### Constructor Parameters - **gcode** (str) - Required - The full G-code content as a string. Unlike parse_gcode_lines, a file-like object is not accepted here. - **include_comments** (bool) - Optional - Default: False - Whether comment-only lines are included in lines (same semantics as parse_gcode_lines). ### Instance Attributes - **gcode** (str) - The input string, stored verbatim. - **include_comments** (bool) - The constructor flag, stored verbatim. - **lines** (list[GcodeLine]) - Eagerly computed by list(parse_gcode_lines(self.gcode, self.include_comments)) at construction time. ### Warnings - **DeprecationWarning** - Always, on every construction. Message: "GcodeParser is deprecated and not recommended. Use parse_gcode_lines() instead." ### Example ```python from gcodeparser import GcodeParser parser = GcodeParser("G21\nG1 X10 Y20 ; move\nM104 S200") for line in parser.lines: print(line.command, line.params) # ('G', 21) {} # ('G', 1) {'X': 10, 'Y': 20} # ('M', 104) {'S': 200} ``` ``` -------------------------------- ### Function signature for parse_gcode_lines Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/parse-gcode-lines.md Signature of the primary entry point that parses G-code from a string, StringIO, or open text file and yields GcodeLine objects lazily. The gcode parameter accepts io.TextIOBase, io.StringIO, or str; include_comments defaults to False. ```python def parse_gcode_lines(gcode: io.TextIOBase | io.StringIO | str, include_comments: bool = False) -> Iterator[GcodeLine]: ``` -------------------------------- ### GcodeParser __init__ with DeprecationWarning Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/errors.md Shows the deprecated constructor that emits a DeprecationWarning on every call. Use parse_gcode_lines() instead. ```python def __init__(self, gcode: str, include_comments=False): warnings.warn( "GcodeParser is deprecated and not recommended. Use parse_gcode_lines() instead.", DeprecationWarning, stacklevel=2, ) ... ``` -------------------------------- ### Import gcodeparser module Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/index.md Import the gcodeparser library to access its public API. The library is zero-dependency and targets Python >=3.10. ```python import gcodeparser ``` -------------------------------- ### Streaming with early exit Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/parse-gcode-lines.md Demonstrates lazy streaming: you can stop consuming the generator early without reading the whole input. Here it breaks after finding the first tool change command (command letter 'T'). ```python from gcodeparser import parse_gcode_lines with open('big.gcode', 'r') as f: for i, line in enumerate(parse_gcode_lines(f)): if line.command[0] == 'T': # tool change print(f"tool change on line {line.line_index}") break ``` -------------------------------- ### Migrating to parse_gcode_lines Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-parser.md Compares the deprecated GcodeParser usage with the recommended parse_gcode_lines approach. Shows before and after code. ```python import warnings from gcodeparser import GcodeParser, parse_gcode_lines # Before (deprecated): with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) lines = GcodeParser(gcode_str).lines # After (recommended): lines = list(parse_gcode_lines(gcode_str)) ``` -------------------------------- ### GcodeLine __post_init__ type computation Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-line.md Automatically computes the `type` field based on the command tuple. Sets `Commands.MOVE` for G0-G3, `Commands.COMMENT` for semicolon, `Commands.TOOLCHANGE` for T, otherwise `Commands.OTHER`. ```python def __post_init__(self): if self.command[0] == "G" and self.command[1] in (0, 1, 2, 3): self.type = Commands.MOVE elif self.command[0] == ";": self.type = Commands.COMMENT elif self.command[0] == "T": self.type = Commands.TOOLCHANGE else: self.type = Commands.OTHER ``` -------------------------------- ### Filtering out flag parameters Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/parse-parameters.md Shows how to identify flag parameters (those with no value) by checking if the value is True. ```python from gcodeparser import parse_parameters params = parse_parameters("X Y1") # X has no value -> flag; Y has value 1 flags = {k for k, v in params.items() if v is True} # flags == {'X'} (Y has value 1, not a flag) ``` -------------------------------- ### GcodeLine get_param method signature Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-line.md Retrieves a parameter value with optional type casting and default. The parameter name is case-sensitive and must be uppercase. Only `KeyError` is caught; cast exceptions propagate. ```python def get_param( self, param: str, return_type: Type[Any] | None = None, default: float | str | bool | None = None, ) -> float | str | bool | None: ``` -------------------------------- ### get_param Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-line.md Retrieves a parameter value from the line's parameters dictionary. Optionally casts the value to a specified type and returns a default if the parameter is not found. ```APIDOC ## get_param ### Description Retrieves a parameter value from the line's parameters dictionary. Optionally casts the value to a specified type and returns a default if the parameter is not found. ### Method get_param ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - `param` (str) - Required - Parameter name (case-insensitive lookup is not performed; pass uppercase name, e.g. "X"). - `return_type` (Type[Any] | None) - Optional - If set, the stored value is type-cast with `return_type(value)` before returning. - `default` (float | str | bool | None) - Optional - Returned when the parameter does not exist. ### Return Value - `float | str | bool | None` - The parameter value (cast to `return_type` if given), or `default` if the key is absent. ### Behavior Notes - Only `KeyError` is caught. If `return_type` is provided and the cast raises, the exception propagates. - A `return_type` of `int` on a float value truncates toward zero; `str` stringifies the numeric value. ### Examples ```python from gcodeparser import GcodeLine line = GcodeLine(command=("G", 1), params={"X": 10.5, "S": "200"}, comment="", line_index=0) line.get_param("X") # 10.5 line.get_param("X", return_type=int) # 10 (truncated) line.get_param("X", return_type=str) # "10.5" line.get_param("S", return_type=float) # 200.0 line.get_param("Y") # None line.get_param("Y", default=0) # 0 ``` ``` -------------------------------- ### Comment Line GcodeLine Structure Source: https://github.com/andyeveritt/gcodeparser/blob/master/README.md Shows the structure of a GcodeLine object for a comment-only line when include_comments is True. The command is (';', None) and params is empty. ```python GcodeLine( command = (';', None), params = {}, comment = 'this comment will only be included if `include_comments=True`', ) ``` -------------------------------- ### GcodeLine command_str property Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-line.md Flattens the command tuple into a string, e.g. `('G', 91)` → `"G91"`. For comment lines, `(';', None)` → `";"`. ```python @property def command_str(self) -> str: return f"{self.command[0]}{self.command[1] if self.command[1] is not None else ''}" ``` ```python from gcodeparser import GcodeLine line = GcodeLine(command=("G", 91), params={"X": 10}, comment="", line_index=0) print(line.command_str) # "G91" ``` -------------------------------- ### include_comments option Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/parse-gcode-lines.md Shows the effect of the include_comments flag. With True, comment-only lines are emitted as GcodeLine with command (';', None); with False, they are skipped. Inline comments on command lines are always included regardless of the flag. ```python from gcodeparser import parse_gcode_lines gcode = """G1 X1 ; this comment is always included ; this comment needs include_comments=True""" lines = list(parse_gcode_lines(gcode, include_comments=True)) # lines[1].command == (';', None) # lines[1].comment == "this comment needs include_comments=True" without = list(parse_gcode_lines(gcode, include_comments=False)) # without has only 1 element: the G1 command ``` -------------------------------- ### gcode_str property implementation Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-line.md Property that reconstructs the original G-code string from a GcodeLine object. Parameters are rendered in insertion order with no space between name and value; flag parameters (True) render as bare letters; comments are appended as '; '; comment-only lines return just the comment text. Renamed from to_gcode() in versions ≤ 0.0.6. ```python @property def gcode_str(self) -> str: command = self.command_str def param_value(param: str) -> str: value = self.get_param(param) is_flag_parameter = value is True if is_flag_parameter: return "" return str(value) params = " ".join(f"{param}{param_value(param)}" for param in self.params.keys()) comment = f"; {self.comment}" if self.comment != "" else "" if command == ";": return comment return f"{command} {params} {comment}".strip() ``` -------------------------------- ### Catching and handling DeprecationWarning Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/errors.md Shows three ways to handle the DeprecationWarning: suppress it, treat it as an error, or avoid the deprecated class entirely. ```python import warnings from gcodeparser import GcodeParser # Option 1: suppress within a block with warnings.catch_warnings(): warnings.simplefilter("ignore", DeprecationWarning) parser = GcodeParser("G28") # Option 2: treat as error during development with warnings.catch_warnings(): warnings.simplefilter("error", DeprecationWarning) try: GcodeParser("G28") except DeprecationWarning: print("deprecated API used") # Recommended: stop using the class entirely from gcodeparser import parse_gcode_lines lines = list(parse_gcode_lines("G28")) ``` -------------------------------- ### Decision logic for infer_element_type Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/infer-element-type.md Shows the internal logic that determines the return type: checks for double quotes or two dots (str), then float pattern, otherwise int. ```python if '"' in element or DOUBLE_DOT_PATTERN.search(element): return str if FLOAT_PATTERN.search(element): return float return int ``` -------------------------------- ### Using GcodeLine with pandas Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/gcode-line.md Passes GcodeLine instances directly to a pandas DataFrame constructor. Reads G-code lines from a file using parse_gcode_lines and converts them to a DataFrame. ```python import pandas as pd from gcodeparser import parse_gcode_lines with open('my_gcode.gcode', 'r') as f: lines = list(parse_gcode_lines(f)) df = pd.DataFrame(lines) ``` -------------------------------- ### PARAMS_PATTERN tokenizer regex Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/parse-parameters.md The regular expression used by the tokenizer to match parameter names and values. It allows optional whitespace, quoted strings, signed numbers, and decimal-leading values. ```python PARAMS_PATTERN = re.compile(r'((?!\d)\w+?)\s*(".*"|(\d+\.?)+|[-+]?\d*\.?\d*)') ``` -------------------------------- ### GcodeLine.get_param - Missing Parameter Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/errors.md When get_param is called with a missing parameter, it returns the default value (None if not given); KeyError is caught internally. This is a deliberate non-error behavior. ```APIDOC ## GcodeLine.get_param - Missing Parameter ### Description When get_param is called with a missing parameter, it returns the default value (None if not given); KeyError is caught internally. This is a deliberate non-error behavior; do not wrap in try/except. ### Behavior - **Situation:** `GcodeLine.get_param` called with a missing param - **Behavior:** Returns `default` (`None` if not given); `KeyError` is caught internally - **Source:** `gcodeparser/__init__.py:69–85` ``` -------------------------------- ### Commands Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/index.md An enum representing the different command types (G, M, T) used in G-code. ```APIDOC ## Commands ### Description An enum representing the different command types (G, M, T) used in G-code. ### Import Path `from gcodeparser import Commands` ### Members - **G** - G-code command (e.g., G1, G28) - **M** - M-code command (e.g., M104, M106) - **T** - Tool command (e.g., T0, T1) ### Example ```python from gcodeparser import Commands print(Commands.G) # Output: Commands.G ``` ``` -------------------------------- ### Reimplementing parse_parameters value conversion Source: https://github.com/andyeveritt/gcodeparser/blob/master/_autodocs/api-reference/infer-element-type.md Provides a custom function that mimics parse_parameters' value conversion, treating empty strings as flag parameters. ```python from gcodeparser import infer_element_type def convert(name: str, raw: str): if raw == "": return True # flag parameter return infer_element_type(raw)(raw) ```