Gmsh Python API
Gmsh is an open-source three-dimensional finite element mesh generator with built-in pre- and post-processing facilities. It is designed to be fast, light, and user-friendly, supporting parametric input and flexible visualization capabilities. The library is actively maintained, with version 4.15.2 released on March 24, 2026, and regular updates.
Common errors
-
AttributeError: dlsym(RTLD_DEFAULT, gmshInitialize)
cause This error typically occurs when the Gmsh Python module cannot find or correctly load the underlying Gmsh shared library. This can happen due to incompatible Python environments, incorrect installation paths, or conflicts with other libraries, especially in bundled applications like FreeCAD.fixEnsure `gmsh` is installed in the correct Python environment. If using a specific application's Python interpreter, verify its compatibility. Sometimes, reinstalling `gmsh` or using `gmsh.initialize(readConfigFiles=False)` can resolve the issue. -
Exception "Could not get last error" raised by gmsh.initialize()
cause This cryptic error during initialization often indicates corrupted Gmsh configuration files or issues with file permissions in the user's Gmsh configuration directory. It prevents the API from starting correctly.fixTry calling `gmsh.initialize(readConfigFiles=False)`. If this works, it confirms a configuration file issue. You might need to locate and delete or reset Gmsh configuration files (e.g., `gmsh.opt` or `gmsh.rc`) in your user's application data directory, or specify a clean working directory. -
Error: Unable to recover the edge XXX on curve YYY (on surface ZZZ)
cause This error points to a problem with the geometric definition, specifically when meshing curves that are not well-defined or form self-intersecting loops. For instance, defining a closed loop with a single spline instead of multiple distinct lines can lead to ambiguity.fixReview the geometry definition. Ensure that closed loops are formed by a sequence of distinct lines/curves. Break down complex splines into simpler segments if necessary, and ensure all entities are correctly oriented and connected. -
OSError: exception: access violation writing 0x00000000XXXXXXXX
cause An 'access violation' error, particularly when calling `gmsh.model.mesh.generate()`, often indicates a low-level memory access problem within the Gmsh library. This can be triggered by complex geometries, specific meshing algorithms, or when generating higher-order elements, especially on Windows.fixSimplify the geometry or reduce meshing complexity (e.g., try generating a 1st-order mesh first). Update Gmsh to the latest version, as these can sometimes be platform-specific bugs. Ensure sufficient memory is available for the meshing operation.
Warnings
- gotcha Always call `gmsh.initialize()` at the beginning of your script and `gmsh.finalize()` at the end. Failing to do so can lead to memory leaks, unexpected behavior, or resource contention if Gmsh is used in subsequent processes.
- gotcha After creating or modifying geometry entities (points, lines, surfaces, volumes), you must call `gmsh.model.geo.synchronize()` (for the built-in kernel) or `gmsh.model.occ.synchronize()` (for the OpenCASCADE kernel) to update the Gmsh internal model before meshing or performing other model operations. Forgetting this step can result in an empty or outdated mesh.
- breaking Beginning with Gmsh version 4.5.0, API errors now consistently throw Python exceptions by default (instead of returning an integer error code). This improves error handling but may break scripts that relied on checking numerical return codes.
- deprecated Gmsh primarily generates triangular or tetrahedral meshes and then uses recombination algorithms to form quadrilaterals or hexahedra. Sometimes, this can result in meshes with mixed element types (e.g., quads and triangles), which may not be supported by all downstream finite element solvers.
Install
-
pip install gmsh -
pip install --upgrade gmsh
Imports
- gmsh
import gmsh
Quickstart
import gmsh
import sys
gmsh.initialize(sys.argv)
try:
gmsh.model.add("square_mesh")
# Define a characteristic length (mesh size)
lc = 0.1
# Create points
p1 = gmsh.model.geo.addPoint(0, 0, 0, lc)
p2 = gmsh.model.geo.addPoint(1, 0, 0, lc)
p3 = gmsh.model.geo.addPoint(1, 1, 0, lc)
p4 = gmsh.model.geo.addPoint(0, 1, 0, lc)
# Create lines
l1 = gmsh.model.geo.addLine(p1, p2)
l2 = gmsh.model.geo.addLine(p2, p3)
l3 = gmsh.model.geo.addLine(p3, p4)
l4 = gmsh.model.geo.addLine(p4, p1)
# Create a curve loop and plane surface
curve_loop = gmsh.model.geo.addCurveLoop([l1, l2, l3, l4])
plane_surface = gmsh.model.geo.addPlaneSurface([curve_loop])
# Synchronize the CAD kernel with the Gmsh model
gmsh.model.geo.synchronize()
# Add a physical group for the surface (optional, but good practice)
gmsh.model.addPhysicalGroup(2, [plane_surface], tag=1)
gmsh.model.setPhysicalName(2, 1, "MySurface")
# Generate a 2D mesh
gmsh.model.mesh.generate(2)
# Write the mesh to a .msh file
gmsh.write("square.msh")
# Optional: uncomment to launch the Gmsh GUI to visualize the mesh
# if '-nopopup' not in sys.argv:
# gmsh.fltk.run()
except Exception as e:
print(f"An error occurred: {e}")
finally:
gmsh.finalize()