Featured post

new redirect for blender.org bpy docs.

http://www.blender.org/api/blender_python_api_current/ As of 10/11 november 2015 we can now link to the current api docs and not be worr...

July 11, 2011

Selecting Edges using some criteria

Below are two methods to select parts of geometry. Sometimes you might want to operate on geometry and don't require user interaction (ie you may not want to be in 'edit mode'). In such cases you might use code similar to the snippet below. to select or unselect edged using bpy.ops you need to be in 'OBJECT' mode. some code to clarify:
import bpy
# this will select every 'even' numbered edge from the list of edges.

# while in object mode, with no edges selected in the underlying object
obj = bpy.context.active_object

bpy.ops.object.mode_set(mode='EDIT')
bpy.context.tool_settings.mesh_select_mode = (False, True, False) # force edges
bpy.ops.mesh.delete(type='ONLY_FACE')

bpy.ops.object.mode_set(mode='OBJECT')

for idx, edge in enumerate(obj.data.edges):
    if (idx % 2) == 0:
        print("selecting", idx)
        edge.select = True
        continue
    
    edge.select = False
        
bpy.ops.object.editmode_toggle()
But sometimes you need to be able to get information about the geometry of an object while in edit mode, and the most convenient way to do that is sing BMesh. The TextEditor templates now has a BMesh demo script which is very interesting for newcomers.
# uses bmesh
# be in edit mode, (edge select mode will be forced)
# any already selected edges will be unselected if they have uneven index.

import bpy
import bmesh

# force edge selection mode
bpy.context.tool_settings.mesh_select_mode = (False, True, False) 

# this will select every 'even' numbered edge from the list of edges.
obj = bpy.context.active_object

bm = bmesh.from_edit_mesh(obj.data)
for edge in bm.edges:
    if edge.index % 2 == 0:
        edge.select = True
        continue
    
    edge.select = False
    



you can think of all kinds of criteria to determine if you want to select an edge (similar technique applies for faces and verts)