execute_code_async
Run long Python computations in FreeCAD without blocking the GUI thread, returning a job_id immediately. Use commit() to apply results safely on the GUI thread.
Instructions
Execute Python code in FreeCAD without waiting for completion.
Use this ONLY for long-running background computations that do NOT touch the
FreeCAD GUI or mutate the FreeCAD document tree directly.
This tool runs the submitted code in a background thread and returns
immediately. Because it does not run on FreeCAD's main GUI thread, the code
must NOT directly call FreeCADGui APIs, manipulate the active view or
selection, create or edit document objects, change object properties, call
doc.recompute(), or save documents. FreeCAD documents and the Coin3D
scenegraph are not thread-safe: writing to them from this thread races the
GUI thread and can wedge FreeCAD's event loop, after which the RPC server
stops responding entirely and FreeCAD must be restarted.
Every document or view write must instead be handed to the GUI thread through
the injected commit() helper:
commit(fn, timeout=120) -> fn's return value
Scripts share a live namespace. Saved functions can use commit() in later
async calls; calling it from execute_code or a GUI callback raises immediately.
Coordinate concurrent scripts that intentionally modify the same variables.
commit() queues fn on the GUI thread, waits for it, and raises RuntimeError if
dispatch fails or times out. Example:
fused = base.fuse(addition).removeSplitter() # slow, safe in background
def apply(): # runs on the GUI thread
obj.Shape = fused
doc.recompute()
commit(apply)
For code that is not dominated by heavy geometry computation, use execute_code
instead. execute_code runs entirely on the FreeCAD GUI thread and is the safe
default for normal FreeCAD automation.
Use execute_code_async only when the heavy part is long-running OCCT geometry
(e.g. fuse/cut/loft on already-fetched shapes) or other CPU-bound computation
that would exceed execute_code's 90 s GUI-thread budget.
Typical usage pattern:
1. Fetch shapes into module-level variables first (via execute_code).
2. Run the heavy computation via execute_code_async.
3. Apply the result inside commit(), or store it in a module-level Python
variable (not in the FreeCAD document) for a later execute_code call.
Performance note: boolean operations against shapes with many faces (e.g. a
ribbed lid) are expensive. Fuse the additions together first, then apply a
single boolean against the heavy shape, and avoid doc.recompute() unless the
dependency graph really needs it.
Args:
code: Background-safe Python code to execute. Use commit(fn) for all
document and view writes.
Returns:
A message with the job_id of the started background execution.
Input Schema
| Name | Required | Description | Default |
|---|---|---|---|
| code | Yes |