Skip to content

Commit

Permalink
gcode_macro: Enable use of Python's math module
Browse files Browse the repository at this point in the history
Jinja2's native math functionality is fairly limited.

Python's math module includes many functions that are useful for
calculations related to 3D printing.
  • Loading branch information
iammattcoleman committed Mar 3, 2025
1 parent 730e595 commit a073762
Show file tree
Hide file tree
Showing 2 changed files with 12 additions and 0 deletions.
10 changes: 10 additions & 0 deletions docs/Command_Templates.md
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,16 @@ gcode:
RESTORE_GCODE_STATE NAME=clean_nozzle_state
```

If more advanced math is required than Jinja2 offers natively,
Python's [math module](https://docs.python.org/3/library/math.html)
is available for use within Jinja2 expressions in G-Code macros:

```
[gcode_macro math_example]
gcode:
REPLY MSG="The square root of 4 is {math.sqrt(4)}."
```

### Macro parameters

It is often useful to inspect parameters passed to the macro when
Expand Down
2 changes: 2 additions & 0 deletions klippy/extras/gcode_macro.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
# This file may be distributed under the terms of the GNU GPLv3 license.
import traceback, logging, ast, copy, json
import jinja2
import math


######################################################################
Expand Down Expand Up @@ -72,6 +73,7 @@ class PrinterGCodeMacro:
def __init__(self, config):
self.printer = config.get_printer()
self.env = jinja2.Environment('{%', '%}', '{', '}')
self.env.globals['math'] = math
def load_template(self, config, option, default=None):
name = "%s:%s" % (config.get_name(), option)
if default is None:
Expand Down

0 comments on commit a073762

Please sign in to comment.