Scripting: Operators

Operators are the basic blender commands. They can be written in python.

Operators Api Docs

Scripting Details

Operators in a blend scene can be made to register on load by activating this menu checkbox:

register_operator

Tutorials

Video Tutorials:

A modal operater adds a new mode to Blender. It basically tells Blender the operator can receive Events.

Api Docs: Event - Event Types

class ModalTimerOperator(bpy.types.Operator):
    """Operator which runs itself from a timer"""
    bl_idname = "wm.modal_timer_operator"
    bl_label = "Modal Timer Operator"

    _timer = None

    def modal(self, context, event):
        if event.type in {'RIGHTMOUSE', 'ESC'}:
            self.cancel(context)
            return {'CANCELLED'}

        if event.type == 'TIMER':
            pass

        return {'PASS_THROUGH'}

    def execute(self, context):
        wm = context.window_manager
        self._timer = wm.event_timer_add(0.1, window=context.window)
        wm.modal_handler_add(self)
        return {'RUNNING_MODAL'}

    def cancel(self, context):
        wm = context.window_manager
        wm.event_timer_remove(self._timer)

Example

import bpy

# everything in an operator is in a class
# that derives from Operator.
# SFA indicates the category
# OT indicates the operator type
class SFA_OT_example(bpy.types.Operator):
    """The Tooltip"""
    # Every operator needs a name and a label.
    bl_idname="sfa.example"
    bl_label="SfA Example"

    # Execute is where you put 
    # the main functionality.
    # This is called directly from python.
    def execute(self, context):
        return {"FINISHED"} # must return this or "CANCELLED"

    # Invoke is called when op is
    # called from a menu or a button.
    # Useful if you need to set up
    # something before executing
    # the actual functionality. 
    def invoke(self, context, event):
        pass

    # Modal is for ops that run
    # in modal form. Useful if it
    # needs to run for a longer time.    
    def modal(self, context, event):
        pass

    # the poll function is called
    # from blender to ask wether this
    # operator is possible to run.
    @classmethod
    def poll(cls, context):
        return True

# Blender needs to know there is a new op,
# so we have to register the class!
def register():
    bpy.utils.register_class(SFA_OT_example)
# and how to forget it.
def unregister():
    bpy.utils.unregister_class(SFA_OT_example)

# If this is run directly, make sure it runs.
if __name__=="__main__":
    register()