Gmsh Python API

4.15.2 · active · verified Thu Apr 16

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

Warnings

Install

Imports

Quickstart

This quickstart generates a simple 2D square mesh using the built-in CAD kernel, saves it to a `.msh` file, and properly initializes and finalizes the Gmsh API. It demonstrates the fundamental steps of geometry definition, synchronization, mesh generation, and output.

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()

view raw JSON →