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:
GCodeCoreG-code generator with complete machine control capabilities.
This class extends
GCodeCoreto 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
statemanager, which maintains and validates the state of various machine subsystems to prevent invalid operations and ensure proper command sequencing.The
traceproperty 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
GCodeCoreclass 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
- origin (
- target (
geometry.Point): Absolute coordinates of the destination point
- target (
- params (
ParamsDict): A dictionary containing movement parameters
- params (
- state (
GState): Current machine state
- 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:
- 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
Nonefor any axis involved.
- Parameters:
- 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:
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:
Deactivates all active tools (spindle, laser, etc.)
Turns off all coolant systems
Adds a comment with the emergency message
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:
- 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
Ffor 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:
- Raises:
IndexError β If the index is out of range
- halt(mode, **kwargs)ο
Pause or stop program execution.
- Parameters:
- Raises:
ToolStateError β If attempting to halt with tool active
CoolantStateError β If attempting to halt with coolant active
- 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.Pointobject 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:
- 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:
- 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:
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 isTrue, otherwisehalt(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:
- Raises:
ValueError β If power is less than 0.0
ValueError β If mode is OFF or was already active
ToolStateError β If attempting invalid mode transition
- 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.
>>> 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:
- 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:
- 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.
- 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:
- 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
Sparameter inM140differently. Useset_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 bedchamber-temperature: Temperature of the chamberhotend-temperature: Temperature of hotendfeed-rate: Movement speed of the tooltool-number: Tool number rangetool-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
Sparameter inM141differently. Use the methodset_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:
- 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:
- 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
Sparameter inM104differently. Useset_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
Pparameter inG4differently. Useset_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 isTrue, otherwisehalt(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
Nonecoordinates 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.
- to_absolute_list(points)ο
Convert a sequence of points to absolute coordinates.
- 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
Nonecoordinates 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.
- 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:
ValueError β If tool number is invalid or mode is OFF
ToolStateError β If tool is currently active
CoolantStateError β If coolant is currently active
- 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:
- Raises:
ValueError β If speed is less than 0.0
ValueError β If mode is OFF or was already active
ToolStateError β If attempting invalid mode transition
- 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 trace: PathTracerο
Interpolated path generation
- property transform: CoordinateTransformerο
Get the current coordinate transformer instance.
- class gscrib.GCodeCore(*args, **kwargs)ο
Bases:
objectCore 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
GCodeBuilderinstead, 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()andrapid()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 themove_absolute()andrapid_absolute()methods may be used.Movement coordinates can be provided as individual X, Y, Z parameters to this methods or as a
geometry.Pointobject. Additionally, all movement methods accept extra G-code parameters as keyword arguments and support an optionalcommentfor annotation.The
transformproperty 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 theget_parameter()method.The
positionproperty 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:
- 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:
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
Ffor 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:
- 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.Pointobject 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:
- 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:
- 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:
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:
- 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:
- 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.
- 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:
- 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
Nonecoordinates 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.
- to_absolute_list(points)ο
Convert a sequence of points to absolute coordinates.
- 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
Nonecoordinates 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.
- 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 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:
objectConfiguration settings for the G-code builders.
This class holds various configuration options for controlling the behavior of G-code generation. See
GCodeCorefor 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:
- direct_write: str | DirectWrite = 'off'ο
- class gscrib.GStateο
Bases:
objectManages 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
- get_parameter(name)ο
Current value of a move parameter by name
- property coolant_mode: CoolantModeο
Get the current coolant mode.
- property distance_mode: DistanceModeο
Get the current distance mode.
- property extrusion_mode: ExtrusionModeο
Get the current extrusion mode.
- property length_units: LengthUnitsο
Get the current length units sytem.
- property temperature_units: TemperatureUnitsο
Get the current temperature units sytem.
- property tool_swap_mode: ToolSwapModeο
Get the current tool swap mode.
- class gscrib.ParamsDict(*args, **kwargs)ο
Bases:
dictA 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ο