gcode-lib
A general-purpose Python library for parsing, analysing, and transforming G-code files.
Supports both plain-text .gcode and Prusa binary .bgcode formats, with a full planar
post-processing toolkit optimised for PrusaSlicer FDM workflows.
Requirements: Python 3.10+ (core uses stdlib only; VTK is optional for STL thumbnail rendering)
Installation
Install from this repository:
python -m pip install .
For editable development:
python -m pip install -e .
Optional STL thumbnail rendering support (VTK):
python -m pip install ".[thumbnails]"
Quick start
import gcode_lib as gl
# Load any .gcode or .bgcode file
gf = gl.load("benchy.gcode")
# Inspect basic statistics
stats = gl.compute_stats(gf.lines)
print(f"Moves: {stats.move_count}")
print(f"Layers: {stats.layer_count}")
print(f"Total extrusion: {stats.total_extrusion:.2f} mm")
bounds = stats.bounds
print(f"Print size: {bounds.width:.1f} x {bounds.height:.1f} mm")
print(f"Centred at: ({bounds.center_x:.1f}, {bounds.center_y:.1f})")
# Estimate print time and filament usage (auto-detects filament type from G-code)
est = gl.estimate_print(gf.lines)
print(f"Print time: {est.time_hms}")
print(f"Filament: {est.filament_length_m:.2f} m / {est.filament_weight_g:.1f} g")
# Shift the print 10 mm to the right, 5 mm forward (arc-safe, no linearization needed)
lines = gl.translate_xy_allow_arcs(gf.lines, dx=10.0, dy=5.0)
gf.lines = lines
gl.save(gf, "benchy_shifted.gcode")
Features
- Loading and saving —
load()/save()for.gcodeand.bgcode,from_text()/to_text(), line and word parsing - State tracking —
ModalState,advance_state(), iterators for moves, arcs, and extruding segments - Transforms — arc linearization, translate, rotate, skew, arbitrary XY transform, layer-selective transforms, G91→G90 conversion, transform analysis
- Bed placement — out-of-bounds detection, recenter/fit to bed
- Statistics — bounding box, move/arc/travel counts, layer iteration, print time and filament usage estimation
- Presets — printer bed dimensions and filament parameters for Prusa printers, auto-detection from G-code
- Utilities — template rendering, thumbnail encoding
- Binary .bgcode — full BGCode read support (None/DEFLATE/Heatshrink + MeatPack) and BGCode v2 writing
- PrusaSlicer CLI — executable discovery, capability probing, single and batch slicing, slicer compatibility notes
- PrusaLink API — printer version, status, job, and G-code upload calls
- API reference — complete function signatures, data classes, and constants
Concepts
GCodeLine
Every line of text becomes a GCodeLine:
line = gl.parse_line("G1 X10.5 Y20.0 E0.12345 F3600 ; perimeter")
print(line.command) # "G1"
print(line.words) # {"X": 10.5, "Y": 20.0, "E": 0.12345, "F": 3600.0}
print(line.comment) # "; perimeter"
print(line.raw) # "G1 X10.5 Y20.0 E0.12345 F3600 ; perimeter"
print(line.is_move) # True (G0 or G1)
print(line.is_arc) # False
print(line.is_blank) # False
words holds X, Y, Z, rotary A, B, C, E, F, I, J, K and R. Comments can be ; or (...), and
text inside either is never read as a word.
ModalState
G-code is stateful. ModalState tracks the printer's current mode and position:
state = gl.ModalState()
print(state.abs_xy) # True (G90 absolute XY by default)
print(state.abs_e) # True (M82 absolute E by default)
print(state.x, state.y, state.z) # 0.0, 0.0, 0.0
GCodeFile
The top-level container returned by load() or from_text():
gf = gl.load("print.gcode")
print(gf.source_format) # "text" or "bgcode"
print(len(gf.lines)) # number of GCodeLine objects
print(len(gf.thumbnails)) # populated for .bgcode and plain-text files with embedded thumbnails
Limitations
- G91 relative XY in transforms:
apply_xy_transform,apply_skew,translate_xy,translate_xy_allow_arcs,rotate_xy,apply_xy_transform_by_layer, andrecenter_to_bedraiseValueErrorif a move/arc with X/Y words is encountered while the modal state is in G91 mode.linearize_arcshandles G91 directly. Useto_absolute_xy()to convert relative segments to absolute before transforming — see G91 and relative-mode handling. - Arc endpoint tracking only.
advance_stateupdates position to the G2/G3 endpoint but does not interpolate intermediate arc positions. Uselinearize_arcsif you need full path coverage. - Helical arcs are not interpolated in Z. Arc geometry is planar. A G2/G3 with a Z word
reaches its final Z at the end of the move, and
estimate_printincludes the Z travel, butlinearize_arcsapplies the whole Z change on the first segment. - No G-code validation. The library parses and transforms; it does not validate that the
resulting G-code is printable or within machine limits. Use
find_oob_movesfor basic bed boundary checking.
Running the tests
python -m pytest tests/ -v
Tests cover I/O, parsing, state tracking, statistics, all transform functions, bed placement, layer iteration, presets, preset detection, template rendering, thumbnail encoding, BGCode round-trips (including Heatshrink decompression and MeatPack decoding), PrusaSlicer CLI and INI helpers, and the PrusaLink client — using only stdlib and pytest. Real VTK thumbnail rendering is also tested on macOS when VTK is installed.
Metadata
Release files for gcode-lib 1.2.2
For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.
Source distribution (sdist)
| File | Size | Uploaded | Provenance | Actions |
|---|---|---|---|---|
| gcode_lib-1.2.2.tar.gz | 1.8 MB | Without provenance | Details for gcode_lib-1.2.2.tar.gz |
Built distribution (wheel)
| File | Interpreter | ABI | Platform | Actions Reset |
|---|---|---|---|---|
| gcode_lib-1.2.2-py3-none-any.whl | Python 3 | none | any | Details for gcode_lib-1.2.2-py3-none-any.whl |
Total release size: 1.9 MB
Release files / gcode_lib-1.2.2.tar.gz
| Download URL | gcode_lib-1.2.2.tar.gz |
|---|---|
| Size | 1.8 MB |
| Tags | Source |
|
SHA-256 checksum How to use checksums |
41027ca22e4a4cee9be4d15b719b4649397b0f39a21672432f83fecd74393e9e
|
|
BLAKE2b-256 checksum How to use checksums |
fa37b64360e06f3a49cd5b883cd0712b71a82645a30965a34abc6860dd491cf8
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.10.11
|
Release files / gcode_lib-1.2.2-py3-none-any.whl
| Download URL | gcode_lib-1.2.2-py3-none-any.whl |
|---|---|
| Size | 77.5 kB |
| Tags | Python 3 |
|
SHA-256 checksum How to use checksums |
54ae0f47275097b877cf9f6173ff2b2daa861d0a2dcb8e6e9f4aca52dc6c236c
|
|
BLAKE2b-256 checksum How to use checksums |
b6dc7ae381bad8a2509e54c3ecae9c2753028e3dd31dc64952d25ed6e321be3f
|
| Upload date | |
|
Uploaded using Trusted Publishing? What is trusted publishing? |
No |
| Uploaded via |
twine/7.0.0 CPython/3.10.11
|
Security for gcode-lib 1.2.2
Provenance
Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.
No provenance found
None of the files in this release were uploaded with provenance metadata.
A note on package security
PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.
To learn more about protecting yourself from malicious actors, visit our package security documentation.