Selecting every face sequentially and performing an action

I am trying to figure out how to create a script that will select a single face, perform an action (in this case, “Remove Doubles UV” with the merge limit set very high) move to the next face and repeat until every face has been hit. From digging around, I found this script on the official blender forums that cycles through faces or vertices with every hotkey press (supposedly alt+P)

#!BPY
"""
Name: 'Select next vertex/edge/face'
Blender: 244
Group: 'Mesh'
Tooltip: 'Select next vertex/edge/face in a mesh'
"""

__author__ = "Stefan Rank"
__version__ = "0.01"
__url__ = ""
__email__ = "[email protected]"
__bpydoc__ = """\
Description:

This script only works if exactly one element (vertex/edge/face) is currently selected.
It then unselects it and selects "the next one" in an arbitrary order.
In this way you can cycle through all elements in a model.

Usage:

- Select one vertex/edge/face in Edit mode.<br>
- Start the script (Object -> Scripts -> Select next vertex/edge/face)<br>

"""

#------------------------------------------------------------
# Select next vertex/edge/face
# (c) 2007 Stefan Rank - [email protected]
#------------------------------------------------------------
# ***** BEGIN GPL LICENSE BLOCK *****
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software Foundation,
# Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307, USA.
#
# ***** END GPL LICENCE BLOCK *****
#------------------------------------------------------------

from Blender import Mesh, Object, Draw, Types, Window
from itertools import chain


def buildnumgroupsdict(mesh):
    numgroupsdict = {}
    for index in xrange(len(mesh.verts)):
        numgroups = len(mesh.getVertexInfluences(index))
        numgroupsdict[numgroups] = 1 + numgroupsdict.get(numgroups, 0)
    return numgroupsdict


def drawstats(mesh, numgroupsdict, debugerror):
    print (debugerror)
    stats = "%sF/%sE/%sV sel:%s/%s/%s" % (
              len(mesh.faces), len(mesh.edges), len(mesh.verts),
              len(mesh.faces.selected()),
              len(mesh.edges.selected()),
              len(mesh.verts.selected()),
             )
    block = ["%s Vs in %s groups" % (val, key)
                for (key, val) in numgroupsdict.items()
            ] + [stats]
    print ('
'.join(block))
    Draw.PupBlock(debugerror.rjust(len(stats)), block)


def askforgroupnum(numgroupsdict):
    msg = "|".join(["Next vertex with n groups%t",
                    "Any number of groups%x9999",
                   ] + ["%s groups%%x%s" % (num, num) for num in numgroupsdict])
    result = Draw.PupMenu(msg)
    if result == 9999:
        result = -1
    return result


def selectnext():
    print ('select next called')
    def bailout(debugerror):
        Draw.PupMenu("Select Next: only works in edit mode with exactly one"
                     " element (vertex/edge/face) of a mesh selected!")
        print (debugerror)
    in_editmode = Window.EditMode()
    if not in_editmode:
        return bailout("not in edit mode!")
    objects = Object.GetSelected()
    if not objects:
        return bailout("no object selected!")
    # online reference claims that we need to leave editmode before
    # getting data from and changing a mesh
    try:
        Window.WaitCursor(1)
        Window.EditMode(0)
        mesh = objects[0].getData(mesh=True)
        if type(mesh) != Types.MeshType:
            return bailout("object is no mesh!")
        selectmode = Mesh.Mode()
        vertmode = selectmode == Mesh.SelectModes.VERTEX
        if vertmode:
            print ('vertexmode')
            elements = mesh.verts
        elif selectmode == Mesh.SelectModes.EDGE:
            print ('edgemode')
            elements = mesh.edges
        elif selectmode == Mesh.SelectModes.FACE:
            print ('facemode')
            elements = mesh.faces
        numgroupsdict = buildnumgroupsdict(mesh)
        selected = elements.selected()
        if len(selected) != 1:
            return drawstats(mesh, numgroupsdict, "not exactly one element selected!")
        if vertmode:
            # ask for the vert criteria
            wantednumgroups = askforgroupnum(numgroupsdict)
            if wantednumgroups is None:
                return
        oldindex = selected[0]
        newindex = (oldindex + 1) % len(elements)
        print ('indexchange: %s --> %s' % (oldindex, newindex))
        elements[oldindex].sel = False
        if not vertmode:
            elements[newindex].sel = True
        else:
            # check for a matching vertex
            def goodvertex(numgroups):
                if wantednumgroups == -1:
                    return True
                if wantednumgroups > 9 and numgroups > 9:
                    return True
                return numgroups == wantednumgroups
            for index in chain(xrange(newindex, len(elements)), xrange(oldindex)):
                numgroups = len(mesh.getVertexInfluences(index))
                if goodvertex(numgroups):
                    elements[index].sel = True
                    break
            else:
                print ('no matching vertex found!')
                elements[oldindex].sel = True
                Draw.PupMenu("No further vertex found that matches the criteria.")
        print ("done select next!")
    finally:
        Window.EditMode(1)
        Window.WaitCursor(0)


selectnext()


It does not function, however. I added parenthesis to all the print statements (the forum post I got it from was from 2007), but blender is no longer giving me any indications of why the code won’t function, only a generic “check console” message (which doesn’t say anything).

Any of you magnanimous fellows care point me in the right direction to get this functioning, or happen to know how to perform commands such as Remove Doubles UV from within a script?

For anyone curious, I am trying to intentionally screw up the UV on my object in order to cause a pixelated texture effect. There are just too many faces to do it by hand.