Run a command on all selected object

I’m trying to create a simple script that takes each object I’ve selected, goes into edit mode, and runs the ‘Snap to Pixels’ command found in the UV/Image editor. Basically so I can select a bunch of objects and fix their UVs from an exporter I’m using.

I don’t know how to handle telling it to use all selected objects, and I don’t know how to get it to use that option. When I run this command (even when manually in Edit mode):

bpy.ops.uv.snap_selected(target='PIXELS')

I get this in return:


Traceback (most recent call last):
  File "<blender_console>", line 1, in <module>
  File "C:\Program Files\Blender Foundation\Blender\2.67\scripts\modules\bpy\ops.py", line 188, in __call__
    ret = op_call(self.idname_py(), None, kw)
RuntimeError: Operator bpy.ops.uv.snap_selected.poll() failed, context is incorrect

Something along these lines?


import bpy


bpy.ops.object.mode_set(mode="OBJECT")
for a in bpy.context.selected_objects:
	bpy.context.scene.objects.active = a
	if a.type == "MESH":
		bpy.ops.object.mode_set(mode="EDIT")
		bpy.ops.mesh.select_all(action="SELECT")
		bpy.ops.uv.select_all(action="SELECT")
		bpy.ops.uv.snap_selected()
		bpy.ops.object.mode_set(mode="OBJECT")

Okay, so all commands work up to: bpy.ops.uv.snap_selected(target=‘PIXELS’)
Then I get the same error message.

poll checks for area.type, is has to be ‘IMAGE_EDITOR’

so you can make it work by:

area_type = bpy.context.area.type
bpy.context.area.type = 'IMAGE_EDITOR'
bpy.ops.uv.snap_selected(target='PIXELS')
bpy.context.area.type = area_type