12
$\begingroup$

In my export script I wish to export all object named 'foo*' in one format, and all objects named 'bar*' in another format.

I could write 2 separate exporters that operate on the selection (so I select all 'foo*' objects and execute FooExporter, rinse and repeat for 'bar*'

But I would rather get it done in one go, with:

fooList = get_objects_starting( 'foo' )
for obj in fooList:
    foo_exporter( obj )

barList = get_objects_starting( 'bar' )
for obj in barList:
    bar_exporter( obj )

How can I get a list of all 'foo*' objects?

$\endgroup$
14
$\begingroup$

If you want to use shell style globbing (*.foo, *.*abc, [ab]*.bar) (as is used in the question), you can use fnmatch, either fnmatch.fnmatchcase or fnmatch.fnmatch for case insensitive matches.

import bpy
import fnmatch

scene = bpy.context.scene

foo_objs = [obj for obj in scene.objects if fnmatch.fnmatchcase(obj.name, "foo*")]

Otherwise you can simply do...

foo_objs = [obj for obj in scene.objects if obj.name.startswith("foo")]

For more powerful pattern matching: check on Python's built-in regular expression (re module)

$\endgroup$
7
$\begingroup$

Just combine list comprehension with str.startswith:

import bpy

foo_objs = [obj for obj in bpy.data.objects if obj.name.startswith("foo")]
$\endgroup$
  • 3
    $\begingroup$ Since the question mentions use for an exporter, bpy.data.objects will give all objects from all scenes. Which you probably wont want, best use scene.objects $\endgroup$ – ideasman42 Jan 10 '14 at 6:39

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.