# Snap cursor python

I'm trying to snap the head of a bone to the cursor position using the script below, but it's not working as shown in the screenshot.

import bpy

C = bpy.context
obj = bpy.data.objects['Armature']
obj.select = True
C.scene.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')

bone = obj.data.edit_bones['Bone']
C.area.type = 'VIEW_3D'
bpy.ops.object.mode_set(mode='OBJECT')
bpy.ops.object.select_all(action='DESELECT')
bpy.data.objects['Empty'].select = True
C.scene.objects.active = bpy.data.objects['Empty']
bpy.ops.view3d.snap_cursor_to_selected()
C.area.type = 'TEXT_EDITOR'
bpy.ops.object.select_all(action='DESELECT')
obj.select = True
C.scene.objects.active = obj
bpy.ops.object.mode_set(mode='EDIT')
bpy.ops.armature.select_all(action='DESELECT')
C.area.type = 'VIEW_3D'
bpy.ops.view3d.snap_selected_to_cursor(use_offset=False)
C.area.type = 'TEXT_EDITOR'


• Do you really want it to snap to the empty, and your're just using the cursor to do it? – cmomoney Feb 18 '17 at 15:58

I don't know exactly why your code isn't working, but I assume the end result that you want is the bone head snapping to the empty. The "friendly", non-ops way to do this would be to put it in an operator:

import bpy

def main(context):
arm = bpy.data.objects['Armature']
empty = bpy.data.objects['Empty']
context.scene.objects.active = arm
#do snapping here
bpy.ops.object.mode_set(mode='EDIT')
bone = arm.data.edit_bones['Bone']
bpy.ops.object.mode_set(mode='OBJECT')

class SimpleOperator(bpy.types.Operator):
"""Tooltip"""
bl_idname = "object.simple_operator"
bl_label = "Simple Object Operator"

@classmethod
def poll(cls, context):
return context.active_object is not None

def execute(self, context):
main(context)
return {'FINISHED'}

def register():
bpy.utils.register_module(__name__)

def unregister():
bpy.utils.unregister_module(__name__)

if __name__ == "__main__":
register()

• how using an operator will solve the problem? – Tak Feb 20 '17 at 10:27
• Using an operator isn't what solves the problem, although it probably eliminates any context related issues. – cmomoney Feb 20 '17 at 15:19