gscrib

Core G-code generation and output management.

This module provides high-level builders for generating G-code commands for CNC machines, 3D printers, laser cutters, and similar devices

class gscrib.GCodeBuilder(*args, **kwargs)

Bases: GCodeCore

G-code generator with complete machine control capabilities.

This class extends GCodeCore to offer comprehensive control over CNC machines and similar devices. It provides a complete machine control solution with advanced features such as state tracking, path interpolation, temperature management and parameter processing.

Key features iclude:

  • Machine state tracking and validation.

  • Coordinate system transformations (rotation, scaling, etc.).

  • Unit and coordinate system management.

  • Tool control (spindle, laser, etc.).

  • Temperature and cooling system management.

  • Basic movement commands (linear, rapid, etc.).

  • Advanced path interpolation (arcs, splines, helixes, etc.).

  • Emergency stop procedures.

  • Multiple output capabilities (file, serial, network).

  • Move hooks for custom parameter processing.

The machine state is tracked by the state manager, which maintains and validates the state of various machine subsystems to prevent invalid operations and ensure proper command sequencing.

The trace property provides access to advanced path interpolation capabilities, supporting complex toolpaths like circular arcs, helixes or splines.

Move hooks can be registered to process and modify movement commands before they are written. Each hook has access to the origin and target points of a move, as well as the current machine state, enabling operations such as:

  • Parameter validation and modification.

  • Feed rate limiting or scaling.

  • Automatic parameter calculations.

  • State-based adjustments (e.g., temperature, tool settings).

  • Safety checks and constraint enforcement.

This class constructor accepts several configuration options. For a detailed description of basic G-code generation and configuration options, refer to the GCodeCore class documentation.

Example

>>> with GCodeMachine(output="outfile.gcode") as g:
>>>     g.rapid_absolute(x=0.0, y=0.0, z=5.0)
>>>     g.tool_on(CLOCKWISE, 1000)
>>>     g.move(z=0.0, F=500)
>>>     g.move(x=10.0, y=10.0, F=1500)
>>>
>>> # Example using a custom hook to extrude filament
>>> def extrude_hook(origin, target, params, state):
>>>     dt = target - origin
>>>     length = math.hypot(dt.x, dt.y, dt.z)
>>>     params.update(E=0.1 * length)
>>>     return params
>>>
>>> with g.move_hook(extrude_hook):
>>>     g.move(x=10, y=0)   # Will add E=1.0
>>>     g.move(x=20, y=10)  # Will add E=1.414
>>>     g.move(x=10, y=10)  # Will add E=1.0
absolute_mode()

Temporarily set absolute distance mode within a context.

This context manager temporarily switches to absolute positioning mode (G90) and automatically restores the previous mode when exiting the context.

Example

>>> with g.absolute_mode():
...     g.move(x=10, y=10)  # Absolute move
...     g.move(x=20, y=20)  # Absolute move
... # Previous distance mode is restored here
add_hook(hook)

Add a permanent move parameter hook.

Hooks are called before each move to process and modify movement parameters. Each hook receives these arguments:

  • origin (geometry.Point):

    Absolute coordinates of the origin point

  • target (geometry.Point):

    Absolute coordinates of the destination point

  • params (ParamsDict):

    A dictionary containing movement parameters

  • state (GState):

    Current machine state

Parameters:

hook (Callable) – Callable that processes movement parameters

Return type:

None

Example

>>> def limit_feed(origin, target, params, state):
>>>     params.update(F=min(params.get('F'), 1000)
>>>     return params
>>>
>>> g.add_hook(limit_feed)
add_writer(writer)

Add a new writer to the list of writers.

Parameters:

writer (BaseWriter) – The writer to add

Return type:

None

annotate(key, value)

Write an annotation comment to the G-code output.

Annotations are a special type of structured comments that can be used by post-processors or other tools to store metadata or configuration information. Useful for storing tool settings, material properties, or processing parameters alongside the G-code.

Parameters:
  • key (str) – Variable name (a valid identifier)

  • value (str) – Variable value (any string)

Raises:

ValueError – If key is not a valid identifier

Return type:

None

Example

>>> g.annotate("tool_diameter", "3.175 mm")
; @set tool_diameter = 3.175 mm
>>> ; @set <key> = <value>
auto_home(point=None, **kwargs)

Move the machine to the home position.

Homes the specified axes (or all axes if none are given) by moving them until they reach their endstops, which are physical switches or sensors marking the machine’s limits.

  • The coordinates provided are always interpreted as absolute in relation to the point where the endstops are triggered.

  • Since the actual stopping point depends on when contact occurs, the current position is set to None for any axis involved.

Parameters:
  • point (Point, optional) – New axis position as a point

  • x (float, optional) – New X-axis position value

  • y (float, optional) – New Y-axis position value

  • z (float, optional) – New Z-axis position value

  • comment (str, optional) – Optional comment to add

  • **kwargs – Additional axis positions

Return type:

None

>>> G28 [X<x>] [Y<y>] [Z<z>] [<param><value> ...]
comment(message, *args)

Write a comment to the G-code output.

Parameters:
  • message (str) – Text of the comment

  • *args – Additional values to include in the comment

Return type:

None

>>> ; <message> <args>
coolant_off()

Deactivate coolant system.

>>> M9
Return type:

None

coolant_on(mode)

Activate coolant system with the specified mode.

Parameters:

mode (CoolantMode | str) – Coolant operation mode to activate

Raises:

ValueError – If mode is OFF or was already active

Return type:

None

>>> M7|M8
current_transform()

Temporarily save the transformation state within a context.

This context manager allows you to temporarily modify the current coordinate system. Any changes made to the coordinate system within the context will be reverted when exiting the context.

Returns:

The current transformer instance.

Return type:

CoordinateTransformer

Example

>>> with g.current_transform():
...     g.transform.translate(10, 0, 0)
...     g.move(x=10, y=10)  # Transformed move
... # Transformation state is restored here
emergency_halt(message, reset=False)

Execute an emergency shutdown sequence and pause execution.

Performs a complete safety shutdown sequence in this order:

  1. Deactivates all active tools (spindle, laser, etc.)

  2. Turns off all coolant systems

  3. Adds a comment with the emergency message

  4. Halts program execution with a mandatory pause or reset

This method ensures safe machine state in emergency situations. The program cannot resume until manually cleared.

Parameters:
  • message (str) – Description of the emergency condition

  • reset (bool) – Perform a full machine reset after halting

Return type:

None

>>> M05
>>> M09
>>> ; Emergency halt: <message>
>>> M00|M30
flush()

Forces any buffered data to be written immediately.

Usually, file writes are buffered to improve performance, reducing the number of disk operations by grouping multiple writes together.

In most cases, manual flushing is not required, as data is flushed automatically when the buffer is full or the file is closed. Use flush when immediate output is needed, such as for logging or when other processes read the file.

Return type:

None

get_parameter(name)

Get the current value of a move parameter by name.

This method retrieves the last used value for a G-code movement parameter. These parameters are stored during move operations and include both standard G-code parameters (like F for feed rate) and any custom parameters passed to move commands.

Parameters:

name (str) – Name of the parameter (case-insensitive)

Returns:

The parameter’s value, or None if the parameter hasn’t been used in any previous move command.

Return type:

Any

get_writer(index=0)

Get a writer by index.

Parameters:

index (int) – Index of the writer to retrieve

Returns:

The writer at the specified index

Return type:

BaseWriter

Raises:

IndexError – If the index is out of range

halt(mode, **kwargs)

Pause or stop program execution.

Parameters:
  • mode (HaltMode | str) – Type of halt to perform

  • **kwargs – Arbitrary command parameters

Raises:
Return type:

None

>>> M0|M1|M2|M30|M60|M109|M190|M191 [<param><value> ...]
move(point=None, **kwargs)

Execute a controlled linear move to the specified location.

The target position can be specified either as a geometry.Point object or as individual x, y, z coordinates. Additional movement parameters can be provided as keyword arguments. The move will be relative or absolute based on the current distance mode.

Parameters:
  • point (Point, optional) – Target position as a point

  • x (float, optional) – Target X-axis position

  • y (float, optional) – Target Y-axis position

  • z (float, optional) – Target Z-axis position

  • comment (str, optional) – Optional comment to add

  • **kwargs – Additional G-code parameters

Return type:

None

>>> G1 [X<x>] [Y<y>] [Z<z>] [<param><value> ...]
move_absolute(point=None, **kwargs)

Execute a controlled move to absolute coordinates.

Performs a coordinated linear move to the specified absolute coordinates, bypassing any active coordinate system transformations. This method temporarily switches to absolute positioning mode if relative mode is active.

Parameters:
  • point (Point, optional) – Target position as a point

  • x (float, optional) – Target X-axis position

  • y (float, optional) – Target Y-axis position

  • z (float, optional) – Target Z-axis position

  • comment (str, optional) – Optional comment to add

  • **kwargs – Additional G-code parameters

Return type:

None

>>> G1 [X<x>] [Y<y>] [Z<z>] [<param><value> ...]
move_hook(hook)

Temporarily enable a move parameter hook.

Parameters:

hook (Callable) – Callable that processes movement parameters

Example

>>> with g.move_hook(extrude_hook):  # Adds a hook
>>>     g.move(x=10, y=0)  # Will add E=1.0
>>> # Hook is removed automatically here
named_transform(name)

Temporarily restore a transformation state within a context.

This context manager allows you to temporarily modify the current coordinate system. Any changes made to the coordinate system within the context will be reverted when exiting the context.

Parameters:

name (str) – Name of the saved transformation state

Raises:

KeyError – If the named state does not exist

Returns:

The current transformer instance.

Return type:

CoordinateTransformer

Example

>>> with g.named_transform("my_transform"):
...     g.move(x=10, y=10)  # Transformed move
... # Transformation state is restored here
pause(optional=False)

Pause program execution.

Invokes halt(HaltMode.OPTIONAL_PAUSE) if optional is True, otherwise halt(HaltMode.PAUSE).

Parameters:

optional (bool) – If True, pause is optional

Return type:

None

>>> M00|M01
power_off()

Power off the current tool.

>>> M5
Return type:

None

power_on(mode, power)

Activate the tool with specified mode and power.

The power parameter represents tool-specific values that vary by machine type, such as:

  • Laser power output (typically 0-100%)

  • Other similar power settings

Parameters:
  • mode (PowerMode | str) – Power mode of the tool

  • power (float) – Power level for the tool (must be >= 0.0)

Raises:
Return type:

None

>>> S<power> M3|M4
probe(mode, point=None, **kwargs)

Execute a probe move to the specified location.

A probe move will continue until contact is made or the target point is reached. Since the actual stopping point depends on when contact occurs, the current position is set to unknown (None) for any axis involved in the movement.

Parameters:
  • mode (ProbingMode | str) – Type of probe to perform

  • point (Point, optional) – Target position as a point

  • x (float, optional) – Target X-axis position

  • y (float, optional) – Target Y-axis position

  • z (float, optional) – Target Z-axis position

  • comment (str, optional) – Comment to include in the move

  • **kwargs – Additional G-code parameters

Return type:

None

>>> G38.2|G38.3|G38.4|G38.5 [X<x>] [Y<y>] [Z<z>] [<param><value> ...]
query(mode)

Query the machine for its current state.

This command is used to request information from the machine about its current state, such as position or temperatures.

Parameters:

mode (QueryMode | str) – The state to query

Return type:

None

>>> M105|M114
rapid(point=None, **kwargs)

Execute a rapid move to the specified location.

Performs a maximum-speed, uncoordinated move where each axis moves independently at its maximum rate to reach the target position. This is typically used for non-cutting movements like positioning or tool changes.

Parameters:
  • point (Point, optional) – Target position as a point

  • x (float, optional) – Target X-axis position

  • y (float, optional) – Target Y-axis position

  • z (float, optional) – Target Z-axis position

  • comment (str, optional) – Optional comment to add

  • **kwargs – Additional G-code parameters

Return type:

None

>>> G0 [X<x>] [Y<y>] [Z<z>] [<param><value> ...]
rapid_absolute(point=None, **kwargs)

Execute a rapid positioning move to absolute coordinates.

Performs a maximum-speed move to the specified absolute coordinates, bypassing any active coordinate system transformations. This method temporarily switches to absolute positioning mode if relative mode is active.

Parameters:
  • point (Point, optional) – Target position as a point

  • x (float, optional) – Target X-axis position

  • y (float, optional) – Target Y-axis position

  • z (float, optional) – Target Z-axis position

  • comment (str, optional) – Optional comment to add

  • **kwargs – Additional G-code parameters

Return type:

None

>>> G0 [X<x>] [Y<y>] [Z<z>] [<param><value> ...]
relative_mode()

Temporarily set relative distance mode within a context.

This context manager temporarily switches to relative positioning mode (G91) and automatically restores the previous mode when exiting the context.

Example

>>> with g.relative_mode():
...     g.move(x=10, y=10)  # Relative move
...     g.move(x=20, y=20)  # Relative move
... # Previous distance mode is restored here
remove_hook(hook)

Remove a previously added move parameter hook.

Parameters:

hook (Callable) – Callable to remove

Return type:

None

Example

>>> g.remove_hook(limit_feed)
remove_writer(writer)

Remove a writer from the list of writers.

Parameters:

writer (BaseWriter) – The writer to remove

Return type:

None

rename_axis(axis, label)

Rename an axis label in the G-code output.

Parameters:
  • axis (Axis | str) – Axis to rename (x, y, or z)

  • label (str) – New label for the axis

Return type:

None

set_axis(point=None, **kwargs)

Set the current position without moving the head.

This command changes the machine’s coordinate system by setting the current position to the specified values without any physical movement. It’s commonly used to set a new reference point or to reset axis positions.

Parameters:
  • point (Point, optional) – New axis position as a point

  • x (float, optional) – New X-axis position value

  • y (float, optional) – New Y-axis position value

  • z (float, optional) – New Z-axis position value

  • comment (str, optional) – Optional comment to add

  • **kwargs – Additional axis positions

Return type:

None

>>> G92 [X<x>] [Y<y>] [Z<z>] [<axis><value> ...]
set_bed_temperature(temperature)

Set the temperature of the bed and return immediately.

Different machine controllers interpret the S parameter in M140 differently. Use set_temperature_units() to set the correct temperature units for your specific controller.

Parameters:

temperature (float) – Target temperature

Return type:

None

>>> M140 S<temperature>
set_bounds(name, min, max)

Set the allowed range (bounds) for a device property.

Bounds define the minimum and maximum values that a property can accept. This is useful for validation and safety checks, ensuring that any values used during operation stay within a defined and expected range.

Supported properties:
  • axes: Position limits (x, y, z)

  • bed-temperature: Temperature of the bed

  • chamber-temperature: Temperature of the chamber

  • hotend-temperature: Temperature of hotend

  • feed-rate: Movement speed of the tool

  • tool-number: Tool number range

  • tool-power: Output power of the tool

Parameters:
  • name (str) – The name of the property to constrain.

  • min (Bound) – The minimum allowed value.

  • max (Bound) – The maximum allowed value.

Raises:
  • ValueError – If bounds are not valid or property is unknown.

  • TypeError – If the type of min/max is incorrect.

Return type:

None

Example

>>> g.set_bounds("feed-rate", min=100, max=1000)
>>> g.set_bounds("axes", min=(0, 0, -10), max=(20, 20, 10))
>>> g.move(x=-100)  # Raises a ValueError exception
set_chamber_temperature(temperature)

Set the temperature of the chamber and return immediately.

Different machine controllers interpret the S parameter in M141 differently. Use the method set_temperature_units() to set the correct temperature units for your specific controller.

Parameters:

temperature (float) – Target temperature

Return type:

None

>>> M141 S<temperature>
set_direction(direction)

Set the rotation direction for interpolated moves.

Parameters:

direction (Direction | str) – Clockwise or counter-clockwise rotation

Raises:

ValueError – If rotation direction is not valid

Return type:

None

set_distance_mode(mode)

Set the positioning mode for subsequent commands.

Parameters:

mode (DistanceMode | str) – The distance mode to use

Raises:

ValueError – If distance mode is not valid

Return type:

None

>>> G90|G91
set_extrusion_mode(mode)

Set the extrusion mode for subsequent commands.

Parameters:

mode (ExtrusionMode | str) – The extrusion mode to use

Raises:

ValueError – If extrusion mode is not valid

Return type:

None

>>> M82|M83
set_fan_speed(speed, fan_number=0)

Set the speed of the main fan.

Parameters:
  • speed (int) – Fan speed (must be >= 0 and <= 255)

  • fan_number (float) – Fan number (must be >= 0)

Raises:

ValueError – If speed is not in the valid range

Return type:

None

>>> M106 P<fan_number> S<speed>
set_feed_mode(mode)

Set the feed rate mode for subsequent commands.

Parameters:

mode (FeedMode | str) – The feed rate mode to use

Raises:

ValueError – If feed mode is not valid

Return type:

None

>>> G93|G94|G95
set_feed_rate(speed)

Set the feed rate for subsequent commands.

Parameters:

speed (float) – The feed rate in the current units

Raises:

ValueError – If speed is not positive

Return type:

None

>>> F<speed>
set_formatter(formatter)

Set a new G-code formatter.

This method allows you to change the G-code formatter used by the generator. The formatter is responsible for converting commands and parameters into the appropriate string format for output.

Parameters:

formatter (BaseFormatter) – The formatter to use

Return type:

None

set_hotend_temperature(temperature)

Set the temperature of the hotend and return immediately.

Different machine controllers interpret the S parameter in M104 differently. Use set_temperature_units() to set the correct temperature units for your specific controller.

Parameters:

temperature (float) – Target temperature

Return type:

None

>>> M104 S<temperature>
set_length_units(length_units)

Set the unit system for subsequent commands.

Parameters:

length_units (LengthUnits) – The unit system to use

Raises:

ValueError – If length units is not valid

Return type:

None

>>> G20|G21
set_plane(plane)

Select the working plane for machine operations.

Parameters:

plane (Plane) – The plane to use for subsequent operations

Raises:

ValueError – If plane is not valid

Return type:

None

>>> G17|G18|G19
set_resolution(resolution)

Set the resolution for interpolated moves.

Controls the accuracy of path approximation by specifying the minimum length of linear segments used to trace the path.

Parameters:

resolution (float) – Length in current work units

Return type:

None

ValueError:

If the resolution is non-positive.

set_temperature_units(temp_units)

Set the temperature units for subsequent commands.

Parameters:

temp_units (TemperatureUnits) – Temperature units

Raises:

ValueError – If temperature units is not valid

Return type:

None

set_time_units(time_units)

Set the time units for subsequent commands.

Parameters:

time_units (TimeUnits) – Time units (seconds/milliseconds)

Raises:

ValueError – If time units is not valid

Return type:

None

set_tool_power(power)

Set the power level for the current tool.

The power parameter represents tool-specific values that vary by machine type, such as:

  • Spindle rotation speed in RPM

  • Laser power output (typically 0-100%)

  • Other similar power settings

Parameters:

power (float) – Power level for the tool (must be >= 0.0)

Raises:

ValueError – If power is less than 0.0

Return type:

None

>>> S<power>
sleep(duration)

Pause program execution for the specified duration.

Generates a dwell command that pauses program execution. Different machine controllers interpret the P parameter in G4 differently. Use set_time_units() to set the correct time units for your specific controller.

Parameters:

duration (float) – Sleep duration in time units

Raises:

ValueError – If duration is less than zero

Return type:

None

>>> G4 P<seconds|milliseconds>
stop(reset=False)

Stop program execution.

Invokes halt(HaltMode.END_WITH_RESET) if reset is True, otherwise halt(HaltMode.END_WITHOUT_RESET).

Parameters:

reset (bool) – If True, reset the machine

Return type:

None

>>> M02|M30
teardown(wait=True)

Clean up and disconnect all writers.

This method should be called to ensure all writers are properly closed and any pending operations are completed. It is typically called when the builder instance is no longer needed.

Parameters:

wait (bool) – Waits for pending operations to complete

Return type:

None

to_absolute(point)

Convert a point to absolute coordinates.

Calculates the absolute coordinates of a target point based on the current position and positioning mode (relative/absolute). Any None coordinates in the current position are first converted to 0.0 to ensure all returned coordinates have numeric values.

The input is a point object containing target coordinates. In absolute mode, these are the final coordinates. In relative mode, these are offsets from the current position.

Parameters:

point (Point) – Absolute target or relative offset

Returns:

The absolute target position

Return type:

Point

to_absolute_list(points)

Convert a sequence of points to absolute coordinates.

Parameters:

points (Sequence[Point]) – Absolute targets or relative offsets

Returns:

A tuple of absolute target positions

Return type:

Point

to_distance_mode(point)

Convert an absolute point to match current distance mode.

Calculates the coordinates to use in a move command based on the current positioning mode (relative/absolute). Any None coordinates in the current position or the target point are first converted to 0.0 to ensure all returned coordinates have numeric values.

In absolute mode, returns the absolute coordinates. In relative mode, returns the offset from current position.

Parameters:

point (Point) – Target point in absolute coordinates

Returns:

Coordinates matching current positioning mode

Return type:

Point

tool_change(mode, tool_number)

Execute a tool change operation.

Performs a tool change sequence, ensuring proper safety conditions are met before proceeding.

Parameters:
  • mode (ToolSwapMode | str) – Tool change mode to execute

  • tool_number (int) – Tool number to select (must be positive)

Raises:
Return type:

None

>>> T<tool_number> M6
tool_off()

Deactivate the current tool.

>>> M5
Return type:

None

tool_on(mode, speed)

Activate the tool with specified direction and speed.

The speed parameter represents tool-specific values that vary by machine type, such as:

  • Spindle rotation speed in RPM

Parameters:
  • mode (SpinMode | str) – Direction of tool rotation (CW/CCW)

  • speed (float) – Speed for the tool (must be >= 0.0)

Raises:
Return type:

None

>>> S<speed> M3|M4
wait()

Wait for all pending moves to complete.

Invokes halt(HaltMode.WAIT_FOR_MOTION).

This ensures all queued motion commands have been executed before proceeding with subsequent commands. Useful for synchronization points where precise positioning is required.

>>> M400
Return type:

None

write(statement)

Write a raw G-code statement to all configured writers.

Direct use of this method is discouraged as it bypasses all state management. Using this method may lead to inconsistencies between the internal state tracking and the actual machine state. Instead, use the dedicated methods like move(), tool_on(), etc., which properly maintain state and ensure safe operation.

Parameters:

statement (str) – The raw G-code statement to write

Raises:

DeviceError – If writing to any output fails

Return type:

None

Example

>>> g = GCodeCore()
>>> g.write("G1 X10 Y20") # Bypasses state tracking
>>> g.move(x=10, y=20) # Proper state management
property distance_mode: DistanceMode

Get the current positioning mode.

property format: BaseFormatter

Get the current G-code formatter instance.

property position: Point

Get the current absolute positions of the axes.

property state: GState

Current machine state.

property trace: PathTracer

Interpolated path generation

property transform: CoordinateTransformer

Get the current coordinate transformer instance.

class gscrib.GCodeCore(*args, **kwargs)

Bases: object

Core class for generating G-code output.

This class provides the fundamental components for generating and outputting G-code, including formatting, coordinate transformations, and support for various output destinations.

It offers the core functionality necessary for G-code generation and is designed to be extended when building custom G-code builders. For most purposes, it is recommended to use GCodeBuilder instead, as it extends this base class with a more comprehensive set of G-code commands and enhanced state management features.

Key responsibilities of this class include:

  • Formatting and writing G-code instructions.

  • Basic movement commands (linear and rapid moves).

  • Position tracking and distance mode management.

  • Coordinate system transformations (rotation, scaling, etc).

  • Support for multiple output methods (file, serial, network, etc).

Basic movement methods include move() and rapid() for linear and rapid moves, respectively. These methods automatically apply any active transformations before outputting the corresponding G-code. To bypass transformations when moving to absolute coordinates the move_absolute() and rapid_absolute() methods may be used.

Movement coordinates can be provided as individual X, Y, Z parameters to this methods or as a geometry.Point object. Additionally, all movement methods accept extra G-code parameters as keyword arguments and support an optional comment for annotation.

The transform property gives access to the coordinate transformer, enabling operations such as translation, rotation, and scaling of the coordinate system. Note that transformations only apply to the X, Y, and Z axes. While custom axes or parameters may be included in the movement commands, transformations and tracking will be limited to the X, Y, and Z axes. Any other custom parameters can be retrieved via the get_parameter() method.

The position property tracks the current positions of the X, Y, and Z axes, reflecting their absolute positions in the original coordinate system (without any transformations).

The teardown() method should be called when done to properly close connections and clean up resources. However, using the class as a context manager automatically handles this.

This class constructor accepts the following configuration options, which can be provided as keyword arguments or as a dictionary:

  • output (str | TextIO | BinaryIO ):

    Path or file-like object where the generated G-Code will be saved. If not specified defaults to stdout.

  • print_lines (bool) [default: false]:

    Always print lines to stdout, even if an output file is specified.

  • direct_write (str | DirectWrite) [default: β€˜off’]:

    Send G-code to machine (β€˜off’, β€˜socket’ or β€˜serial’).

  • host (str) [default: localhost]:

    Hostname/IP for network connection when using socket mode.

  • port (int) [default: 8000]:

    Port number for network/serial communication.

  • baudrate (int) [default: 250000]:

    Baud rate for serial connection.

  • decimal_places (str) [default: 5]:

    Maximum number of decimal places in numeric output.

  • comment_symbols (str) [default: β€˜;’]:

    Characters used to mark comments in G-code.

  • line_endings (str) [default: β€˜os’]:

    Line ending characters (use β€˜os’ for system default).

  • x_axis (str) [default: β€˜X’]:

    Custom label for X axis in G-code output.

  • y_axis (str) [default: β€˜Y’]:

    Custom label for Y axis in G-code output.

  • z_axis (str) [default: β€˜Z’]:

    Custom label for Z axis in G-code output.

Example

>>> with GCodeCore(output="outfile.gcode") as g:
...     g.set_distance_mode("absolute")
...     g.move(x=10, y=10)  # Linear move to (10, 10)
...     g.rapid(z=5)        # Rapid move up to Z=5
Parameters:

kwargs (Any)

absolute_mode()

Temporarily set absolute distance mode within a context.

This context manager temporarily switches to absolute positioning mode (G90) and automatically restores the previous mode when exiting the context.

Example

>>> with g.absolute_mode():
...     g.move(x=10, y=10)  # Absolute move
...     g.move(x=20, y=20)  # Absolute move
... # Previous distance mode is restored here
add_writer(writer)

Add a new writer to the list of writers.

Parameters:

writer (BaseWriter) – The writer to add

Return type:

None

annotate(key, value)

Write an annotation comment to the G-code output.

Annotations are a special type of structured comments that can be used by post-processors or other tools to store metadata or configuration information. Useful for storing tool settings, material properties, or processing parameters alongside the G-code.

Parameters:
  • key (str) – Variable name (a valid identifier)

  • value (str) – Variable value (any string)

Raises:

ValueError – If key is not a valid identifier

Return type:

None

Example

>>> g.annotate("tool_diameter", "3.175 mm")
; @set tool_diameter = 3.175 mm
>>> ; @set <key> = <value>
comment(message, *args)

Write a comment to the G-code output.

Parameters:
  • message (str) – Text of the comment

  • *args – Additional values to include in the comment

Return type:

None

>>> ; <message> <args>
current_transform()

Temporarily save the transformation state within a context.

This context manager allows you to temporarily modify the current coordinate system. Any changes made to the coordinate system within the context will be reverted when exiting the context.

Returns:

The current transformer instance.

Return type:

CoordinateTransformer

Example

>>> with g.current_transform():
...     g.transform.translate(10, 0, 0)
...     g.move(x=10, y=10)  # Transformed move
... # Transformation state is restored here
flush()

Forces any buffered data to be written immediately.

Usually, file writes are buffered to improve performance, reducing the number of disk operations by grouping multiple writes together.

In most cases, manual flushing is not required, as data is flushed automatically when the buffer is full or the file is closed. Use flush when immediate output is needed, such as for logging or when other processes read the file.

Return type:

None

get_parameter(name)

Get the current value of a move parameter by name.

This method retrieves the last used value for a G-code movement parameter. These parameters are stored during move operations and include both standard G-code parameters (like F for feed rate) and any custom parameters passed to move commands.

Parameters:

name (str) – Name of the parameter (case-insensitive)

Returns:

The parameter’s value, or None if the parameter hasn’t been used in any previous move command.

Return type:

Any

get_writer(index=0)

Get a writer by index.

Parameters:

index (int) – Index of the writer to retrieve

Returns:

The writer at the specified index

Return type:

BaseWriter

Raises:

IndexError – If the index is out of range

move(point=None, **kwargs)

Execute a controlled linear move to the specified location.

The target position can be specified either as a geometry.Point object or as individual x, y, z coordinates. Additional movement parameters can be provided as keyword arguments. The move will be relative or absolute based on the current distance mode.

Parameters:
  • point (Point, optional) – Target position as a point

  • x (float, optional) – Target X-axis position

  • y (float, optional) – Target Y-axis position

  • z (float, optional) – Target Z-axis position

  • comment (str, optional) – Optional comment to add

  • **kwargs – Additional G-code parameters

Return type:

None

>>> G1 [X<x>] [Y<y>] [Z<z>] [<param><value> ...]
move_absolute(point=None, **kwargs)

Execute a controlled move to absolute coordinates.

Performs a coordinated linear move to the specified absolute coordinates, bypassing any active coordinate system transformations. This method temporarily switches to absolute positioning mode if relative mode is active.

Parameters:
  • point (Point, optional) – Target position as a point

  • x (float, optional) – Target X-axis position

  • y (float, optional) – Target Y-axis position

  • z (float, optional) – Target Z-axis position

  • comment (str, optional) – Optional comment to add

  • **kwargs – Additional G-code parameters

Return type:

None

>>> G1 [X<x>] [Y<y>] [Z<z>] [<param><value> ...]
named_transform(name)

Temporarily restore a transformation state within a context.

This context manager allows you to temporarily modify the current coordinate system. Any changes made to the coordinate system within the context will be reverted when exiting the context.

Parameters:

name (str) – Name of the saved transformation state

Raises:

KeyError – If the named state does not exist

Returns:

The current transformer instance.

Return type:

CoordinateTransformer

Example

>>> with g.named_transform("my_transform"):
...     g.move(x=10, y=10)  # Transformed move
... # Transformation state is restored here
rapid(point=None, **kwargs)

Execute a rapid move to the specified location.

Performs a maximum-speed, uncoordinated move where each axis moves independently at its maximum rate to reach the target position. This is typically used for non-cutting movements like positioning or tool changes.

Parameters:
  • point (Point, optional) – Target position as a point

  • x (float, optional) – Target X-axis position

  • y (float, optional) – Target Y-axis position

  • z (float, optional) – Target Z-axis position

  • comment (str, optional) – Optional comment to add

  • **kwargs – Additional G-code parameters

Return type:

None

>>> G0 [X<x>] [Y<y>] [Z<z>] [<param><value> ...]
rapid_absolute(point=None, **kwargs)

Execute a rapid positioning move to absolute coordinates.

Performs a maximum-speed move to the specified absolute coordinates, bypassing any active coordinate system transformations. This method temporarily switches to absolute positioning mode if relative mode is active.

Parameters:
  • point (Point, optional) – Target position as a point

  • x (float, optional) – Target X-axis position

  • y (float, optional) – Target Y-axis position

  • z (float, optional) – Target Z-axis position

  • comment (str, optional) – Optional comment to add

  • **kwargs – Additional G-code parameters

Return type:

None

>>> G0 [X<x>] [Y<y>] [Z<z>] [<param><value> ...]
relative_mode()

Temporarily set relative distance mode within a context.

This context manager temporarily switches to relative positioning mode (G91) and automatically restores the previous mode when exiting the context.

Example

>>> with g.relative_mode():
...     g.move(x=10, y=10)  # Relative move
...     g.move(x=20, y=20)  # Relative move
... # Previous distance mode is restored here
remove_writer(writer)

Remove a writer from the list of writers.

Parameters:

writer (BaseWriter) – The writer to remove

Return type:

None

rename_axis(axis, label)

Rename an axis label in the G-code output.

Parameters:
  • axis (Axis | str) – Axis to rename (x, y, or z)

  • label (str) – New label for the axis

Return type:

None

set_axis(point=None, **kwargs)

Set the current position without moving the head.

This command changes the machine’s coordinate system by setting the current position to the specified values without any physical movement. It’s commonly used to set a new reference point or to reset axis positions.

Parameters:
  • point (Point, optional) – New axis position as a point

  • x (float, optional) – New X-axis position value

  • y (float, optional) – New Y-axis position value

  • z (float, optional) – New Z-axis position value

  • comment (str, optional) – Optional comment to add

  • **kwargs – Additional axis positions

Return type:

None

>>> G92 [X<x>] [Y<y>] [Z<z>] [<axis><value> ...]
set_distance_mode(mode)

Set the positioning mode for subsequent commands.

Parameters:

mode (DistanceMode | str) – The distance mode (absolute/relative)

Raises:

ValueError – If distance mode is not valid

Return type:

None

>>> G90|G91
set_formatter(formatter)

Set a new G-code formatter.

This method allows you to change the G-code formatter used by the generator. The formatter is responsible for converting commands and parameters into the appropriate string format for output.

Parameters:

formatter (BaseFormatter) – The formatter to use

Return type:

None

teardown(wait=True)

Clean up and disconnect all writers.

This method should be called to ensure all writers are properly closed and any pending operations are completed. It is typically called when the builder instance is no longer needed.

Parameters:

wait (bool) – Waits for pending operations to complete

Return type:

None

to_absolute(point)

Convert a point to absolute coordinates.

Calculates the absolute coordinates of a target point based on the current position and positioning mode (relative/absolute). Any None coordinates in the current position are first converted to 0.0 to ensure all returned coordinates have numeric values.

The input is a point object containing target coordinates. In absolute mode, these are the final coordinates. In relative mode, these are offsets from the current position.

Parameters:

point (Point) – Absolute target or relative offset

Returns:

The absolute target position

Return type:

Point

to_absolute_list(points)

Convert a sequence of points to absolute coordinates.

Parameters:

points (Sequence[Point]) – Absolute targets or relative offsets

Returns:

A tuple of absolute target positions

Return type:

Point

to_distance_mode(point)

Convert an absolute point to match current distance mode.

Calculates the coordinates to use in a move command based on the current positioning mode (relative/absolute). Any None coordinates in the current position or the target point are first converted to 0.0 to ensure all returned coordinates have numeric values.

In absolute mode, returns the absolute coordinates. In relative mode, returns the offset from current position.

Parameters:

point (Point) – Target point in absolute coordinates

Returns:

Coordinates matching current positioning mode

Return type:

Point

write(statement)

Write a raw G-code statement to all configured writers.

Direct use of this method is discouraged as it bypasses all state management. Using this method may lead to inconsistencies between the internal state tracking and the actual machine state. Instead, use the dedicated methods like move(), tool_on(), etc., which properly maintain state and ensure safe operation.

Parameters:

statement (str) – The raw G-code statement to write

Raises:
  • GCodeError – If the internal state is inconsistent

  • DeviceError – If writing to any output fails

Return type:

None

Example

>>> g = GCodeCore()
>>> g.write("G1 X10 Y20") # Bypasses state tracking
>>> g.move(x=10, y=20) # Proper state management
property distance_mode: DistanceMode

Get the current positioning mode.

property format: BaseFormatter

Get the current G-code formatter instance.

property position: Point

Get the current absolute positions of the axes.

property transform: CoordinateTransformer

Get the current coordinate transformer instance.

class gscrib.GConfig(output=None, decimal_places=5, comment_symbols=';', line_endings='os', print_lines=False, direct_write=DirectWrite.OFF, host='localhost', port=8000, baudrate=250000, x_axis='X', y_axis='Y', z_axis='Z')

Bases: object

Configuration settings for the G-code builders.

This class holds various configuration options for controlling the behavior of G-code generation. See GCodeCore for details on how these settings are used in the G-code generation process.

Example

>>> g = GCodeCore({
...     "output": "filename.gcode",
...     "decimal_places": 5,
...     "comment_symbols": ";",
... })
Parameters:
classmethod from_object(config)

Instantiate from an object or dictionary.

Parameters:

config – Any object with attributes or a dictionary

Returns:

A new configuration instance

Return type:

GConfig

baudrate: int = 250000
comment_symbols: str = ';'
decimal_places: int = 5
direct_write: str | DirectWrite = 'off'
host: str = 'localhost'
line_endings: str = 'os'
output: str | TextIO | BinaryIO | None = None
port: int | str = 8000
print_lines: bool | str = False
x_axis: str = 'X'
y_axis: str = 'Y'
z_axis: str = 'Z'
class gscrib.GState

Bases: object

Manages and tracks the state of the G-code machine.

This class maintains the current state of various G-code machine parameters. It provides methods to retrieve and safely modify these states while enforcing validation rules.

get_bounds(name)

Current user defined bounds for a property

Parameters:

name (str)

Return type:

Any

get_parameter(name)

Current value of a move parameter by name

Parameters:

name (str)

Return type:

Any

property coolant_mode: CoolantMode

Get the current coolant mode.

property direction: Direction

Get the current direction for interpolated moves.

property distance_mode: DistanceMode

Get the current distance mode.

property extrusion_mode: ExtrusionMode

Get the current extrusion mode.

property feed_mode: FeedMode

Get the current feed mode.

property feed_rate: float

Get the current feed rate.

property halt_mode: HaltMode

Get the current halt mode.

property is_coolant_active: bool

Check if coolant is currently active.

property is_tool_active: bool

Check if tool is currently active.

property length_units: LengthUnits

Get the current length units sytem.

property plane: Plane

Get the current working plane.

property position: Point

Current absolute position of the axes.

property power_mode: PowerMode

Get the current power mode.

property resolution: float

Get the current resolution for interpolated moves.

property spin_mode: SpinMode

Get the current spin mode.

property target_bed_temperature: float

Get the current target bed temperature.

property target_chamber_temperature: float

Get the current target chamber temperature.

property target_hotend_temperature: float

Get the current target hotend temperature.

property temperature_units: TemperatureUnits

Get the current temperature units sytem.

property time_units: TimeUnits

Get the current time units sytem.

property tool_number: int

Get the current tool number.

property tool_power: float

Get the current tool power.

property tool_swap_mode: ToolSwapMode

Get the current tool swap mode.

class gscrib.ParamsDict(*args, **kwargs)

Bases: dict

A case-insensitive dictionary for G-code movement parameters.

This dictionary subclass automatically converts all keys to uppercase, allowing case-insensitive access to movement parameters. This is useful for G-code generation where parameter letters are traditionally case-insensitive.

Examples

>>> params = MoveParams()
>>> params['F'] = 1000
>>> params['f']  # Returns 1000
>>> params['F']  # Returns 1000
clear() None.  Remove all items from D.
copy() a shallow copy of D
classmethod fromkeys(iterable, value=None, /)

Create a new dictionary with keys from iterable and values set to value.

get(key, default=None)

Get value, return default if not found.

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
pop(k[, d]) v, remove specified key and return the corresponding value.

If the key is not found, return the default if given; otherwise, raise a KeyError.

popitem()

Remove and return a (key, value) pair as a 2-tuple.

Pairs are returned in LIFO (last-in, first-out) order. Raises KeyError if the dict is empty.

setdefault(key, default=None)

Set default value if key not found.

update(*args, **kwargs)

Update dictionary converting all keys to uppercase.

values() an object providing a view on D's values