I've been scouring the Blender Python API docs for a way to get access to the mesh data that is displayed in the view-port. (with modifiers applied - WYSIWYG)
For reference, this was possible with the 2.4x API's Mesh.getFromObject
method.
The option to apply modifiers is common for exporters included with Blender, so you can check how they do it.
Typically you can use the Object.to_mesh
function, which returns a new mesh. You can manipulate it without distructively editing the user's data.
import bpy
# --- setup variables ---
context = bpy.context
scene = context.scene
# assume we have an object with geometry, nurbs, metaball, curves... _not_ a lamp
obj = context.object
# --- get a mesh from the object ---
apply_modifiers = True
settings = 'PREVIEW'
mesh = obj.to_mesh(scene, apply_modifiers, settings)
# ... do something with the mesh ...
It's important to remove the mesh, unless you have explicitly assigned it to an object. Otherwise it will be stored in Blender until the file is saved and loaded again.
# optionally remove it
bpy.data.meshes.remove(mesh)
It appears that the to_mesh function no longer has an "apply_modifiers" argument in Blender API 2.80. Instead, you will need to retrieve the dependencies graph ("depsgraph") and use it to get the "evaluated" object:
depsgraph = bpy.context.evaluated_depsgraph_get()
obj = context.object
object_eval = obj.evaluated_get(depsgraph)
The new, evaluated object will have a mesh with the modifiers applied. If needed, you can make a copy of it via:
mesh_from_eval = bpy.data.meshes.new_from_object(object_eval)
for some examples and further info, see: https://docs.blender.org/api/current/bpy.types.Depsgraph.html