Rendering and setting keyframes confusion?

I am new to Blender and I’m having a bit of a tough time understanding its key concepts. I am using Blender 2.82 and working with Python scripting. My project consists of using Python to do the following:

  1. Move object slightly
  2. Take picture with camera 1, camera 2, camera 3, and camera 4
  3. Repeat

I had a script that did that. However, I wanted to save the position of my object (a sphere) every time I changed it during the loop in an animation, so I could later see what I did. When trying to insert keyframes for animation in my loop, it seems as if my sphere didn’t move. Below is my code. When I remove the lines that include “frame_set” and “keyframe_insert”, my sphere moves as I can see from my rendered images. I think I am confusing some kind of concept… Any help would be appreciated. The goal of this is to produce the images I would obtain from four cameras placed around an object, that is moving, so as to simulate a mocap system.


import bpy, bgl, blf,sys
import numpy as np
from bpy import data, ops, props, types, context
print("\nThis Python script will render your scene with all available cameras")
print("or with camera(s) matching command line argument 'cameras'")
print("")
print("Usage:")
print("Render all cameras:")
print("blender -b your_file.blend -P render_all_cameras.py\n")
print("Render only matching cameras:")
print("blender -b your_file.blend -P render_all_cameras.py  cameras=east\n")

cameraNames=''

# Loop all command line arguments and try to find "cameras=east" or similar
for arg in sys.argv:
    words=arg.split('=')
    if ( words[0] == 'cameras'):
     cameraNames = words[1]

print('rendering cameras containing [' + cameraNames + ']')

print('\nPrint Scenes...')
sceneKey = bpy.data.scenes.keys()[0]
print('Using Scene['  + sceneKey + ']')

# Loop all objects and try to find Cameras
print('Looping Cameras')
#c=0
bpy.data.scenes[sceneKey].render.image_settings.file_format = 'JPEG'
bpy.data.scenes[sceneKey].cycles.max_bounces=12
bpy.data.scenes[sceneKey].render.tile_x=8
bpy.data.scenes[sceneKey].render.tile_y=8
bpy.data.scenes[sceneKey].cycles.samples = 16
bpy.data.scenes[sceneKey].cycles.caustics_reflective = False
bpy.data.scenes[sceneKey].cycles.caustics_refractive = False



bpy.data.objects['Sphere'].location=[1,1,1] 
frame_num=0
for i in range(0,2): #nframes
    bpy.context.scene.frame_set(frame_num)
    for obj in bpy.data.objects:
        # Find cameras that match cameraNames
        if ( obj.type =='CAMERA') and ( cameraNames == '' or obj.name.find(cameraNames) != -1) :
            print("Rendering scene["+sceneKey+"] with Camera["+obj.name+"]")

          # Set Scenes camera and output filename
            bpy.data.scenes[sceneKey].camera = obj


            bpy.data.scenes[sceneKey].render.filepath = '//'+obj.name+"_"+str(i) 

          # Render Scene and store the scene
            bpy.ops.render.render( write_still=True )

    bpy.data.objects['Sphere'].keyframe_insert(data_path="location",index=-1)
    frame_num+=1
    bpy.data.objects['Sphere'].location=[2,2,1]

print('Done!')