{"id":8199,"library":"gmsh","title":"Gmsh Python API","description":"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.","status":"active","version":"4.15.2","language":"en","source_language":"en","source_url":"https://gitlab.onelab.info/gmsh/gmsh","tags":["meshing","finite element","CAD","geometry","FEM","pre-processing"],"install":[{"cmd":"pip install gmsh","lang":"bash","label":"Install stable release"},{"cmd":"pip install --upgrade gmsh","lang":"bash","label":"Upgrade to latest release"}],"dependencies":[{"reason":"Commonly used for numerical operations and array manipulation in scripts interacting with mesh data.","package":"numpy","optional":true},{"reason":"A versatile mesh I/O library often used to read/write various mesh formats, including .msh files generated by Gmsh, for compatibility with other FEM solvers.","package":"meshio","optional":true},{"reason":"A finite element solver often integrated with Gmsh for mesh generation and subsequent simulations.","package":"dolfinx","optional":true}],"imports":[{"symbol":"gmsh","correct":"import gmsh"}],"quickstart":{"code":"import gmsh\nimport sys\n\ngmsh.initialize(sys.argv)\n\ntry:\n    gmsh.model.add(\"square_mesh\")\n\n    # Define a characteristic length (mesh size)\n    lc = 0.1\n\n    # Create points\n    p1 = gmsh.model.geo.addPoint(0, 0, 0, lc)\n    p2 = gmsh.model.geo.addPoint(1, 0, 0, lc)\n    p3 = gmsh.model.geo.addPoint(1, 1, 0, lc)\n    p4 = gmsh.model.geo.addPoint(0, 1, 0, lc)\n\n    # Create lines\n    l1 = gmsh.model.geo.addLine(p1, p2)\n    l2 = gmsh.model.geo.addLine(p2, p3)\n    l3 = gmsh.model.geo.addLine(p3, p4)\n    l4 = gmsh.model.geo.addLine(p4, p1)\n\n    # Create a curve loop and plane surface\n    curve_loop = gmsh.model.geo.addCurveLoop([l1, l2, l3, l4])\n    plane_surface = gmsh.model.geo.addPlaneSurface([curve_loop])\n\n    # Synchronize the CAD kernel with the Gmsh model\n    gmsh.model.geo.synchronize()\n\n    # Add a physical group for the surface (optional, but good practice)\n    gmsh.model.addPhysicalGroup(2, [plane_surface], tag=1)\n    gmsh.model.setPhysicalName(2, 1, \"MySurface\")\n\n    # Generate a 2D mesh\n    gmsh.model.mesh.generate(2)\n\n    # Write the mesh to a .msh file\n    gmsh.write(\"square.msh\")\n\n    # Optional: uncomment to launch the Gmsh GUI to visualize the mesh\n    # if '-nopopup' not in sys.argv:\n    #     gmsh.fltk.run()\n\nexcept Exception as e:\n    print(f\"An error occurred: {e}\")\nfinally:\n    gmsh.finalize()","lang":"python","description":"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."},"warnings":[{"fix":"Ensure `gmsh.initialize()` is called before any other Gmsh API function and `gmsh.finalize()` is called at script termination, ideally in a `try...finally` block.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Insert `gmsh.model.geo.synchronize()` or `gmsh.model.occ.synchronize()` after a series of geometry creation commands and before mesh generation.","message":"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.","severity":"gotcha","affected_versions":"All versions"},{"fix":"Update scripts to use standard Python `try...except` blocks to catch `Exception` for Gmsh API errors, or disable default exception throwing by setting `gmsh.option.setNumber('General.AbortOnError', 0)` if preferred (though not recommended).","message":"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.","severity":"breaking","affected_versions":">=4.5.0"},{"fix":"Explicitly set meshing options like `gmsh.option.setNumber('Mesh.RecombinationAlgorithm', 2)` and `gmsh.option.setNumber('Mesh.RecombineAll', 1)` to encourage quad/hexa generation, but be aware that mixed elements might still occur. Inspect your mesh output carefully and adjust options or geometry if necessary.","message":"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.","severity":"deprecated","affected_versions":"All versions"}],"env_vars":null,"last_verified":"2026-04-16T00:00:00.000Z","next_check":"2026-07-15T00:00:00.000Z","problems":[{"fix":"Ensure `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.","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.","error":"AttributeError: dlsym(RTLD_DEFAULT, gmshInitialize)"},{"fix":"Try 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.","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.","error":"Exception \"Could not get last error\" raised by gmsh.initialize()"},{"fix":"Review 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.","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.","error":"Error: Unable to recover the edge XXX on curve YYY (on surface ZZZ)"},{"fix":"Simplify 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.","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.","error":"OSError: exception: access violation writing 0x00000000XXXXXXXX"}]}