# Blender Python Console Commands not completing before next one is interpreted?

I'm working with the default Blender file that has single cube object. I'm rotating it with Python and adding keyframes. The problem is that a bpy.ops.transform.rotate() seems to take some time to execute so when I paste in a series of commands a keyframe is created before the rotation actually happens. If I paste commands in one at a time I get my expected animations. Is there a "finished" event, or "wait for last" command I can use?

This code pasted in the Console may show rotations on some of the keyframes and not on others, it is inconsistent.

bpy.context.scene.frame_current = 0
bpy.ops.anim.keyframe_insert()

bpy.context.scene.frame_current = 30

bpy.ops.transform.rotate(value=1.5708, axis=(1, 0, 0), constraint_axis=(True, False, False), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1, release_confirm=False)

bpy.ops.anim.keyframe_insert()

bpy.context.scene.frame_current = 60

bpy.ops.transform.rotate(value=-1.5708, axis=(0, 1, 0), constraint_axis=(False, True, False), constraint_orientation='GLOBAL', mirror=False, proportional='DISABLED', proportional_edit_falloff='SMOOTH', proportional_size=1, release_confirm=False)

bpy.ops.anim.keyframe_insert()

... and so on


Ditch the operators and use the API

Example script, rotates object 90 degrees about z axis. Inserts all keyframes of active keying set at frame 30. Not using any operators or changing the frame, simply set a property and call keyframe_insert.

import bpy
from mathutils import Matrix
context = bpy.context
ob = context.object
scene = context.scene
# emulate rotation op
ob.matrix_world *= R

#emulate ops.anim.keyframe_insert
ks = scene.keying_sets.active
if ks:
ks.refresh()
for p in ks.paths:
# check for entire array (index=-1)
index = -1 if p.use_entire_array else p.array_index
# insert keyframe
ob.keyframe_insert(
p.data_path,
index=index,
frame=30)


A method could be made using methods above that is passed the arguments object angle, axis and frame.

def rot_and_keyframe(ob, angle, axis, frame):
...