rendering cubemaps by code (context error) Need to render animated cubemaps for use in another program. UI allows to save the cubemap of current frame.

Trying to do it in Python. Getting a context error:

import bpy

# remember current frame to switch back after the script is finished
current_frame = bpy.context.scene.frame_current

for i in range(bpy.context.scene.frame_start, bpy.context.scene.frame_end+1):
    # set current frame
    bpy.context.scene.frame_current = i

    # create an image which will store the baked data
    image = bpy.data.images.new(str(i)+'.png', bpy.context.scene.render.resolution_x, bpy.context.scene.render.resolution_y, alpha = 0)
    image.file_format = 'PNG'
    image.filepath = "//"+str(i)+".png"
    #image.save()

    # need to render for some reason to save the cubemap below
    bpy.ops.render.render()

    # save cubemap image
    # needs proper context
    area = bpy.context.area
    old_type = area.type
    area.type = 'PROPERTIES'
    bpy.ops.texture.envmap_save(filepath=str(i)+'.png')
    area.type = old_type

    print ("Frame "+str(i)+" complete")

# switch back to the frame you were on before running this code
bpy.context.scene.frame_current = current_frame
That did the trick for me once the env map image source was set to 'GENERATED'

import bpy

# remember current frame to switch back after the script is finished

context = bpy.context
scene = context.scene
current_frame = scene.frame_current
area = context.area
old_type = area.type
area.type = 'PROPERTIES'
context.space_data.context = 'TEXTURE'

for i in range(scene.frame_start, scene.frame_end+1):
    # set current frame
    scene.frame_set(i)

    # create an image which will store the baked data
    image = bpy.data.images.new(str(i)+'.png', bpy.context.scene.render.resolution_x, bpy.context.scene.render.resolution_y, alpha = 0)
    image.file_format = 'PNG'
    image.filepath = "//"+str(i)+".png"
    #image.save()

    # need to render for some reason to save the cubemap below
    bpy.ops.render.render()

    # save cubemap image
    # needs proper context


    bpy.ops.texture.envmap_save(filepath=str(i)+'.png')


    print ("Frame "+str(i)+" complete")

area.type = old_type
# switch back to the frame you were on before running this code
scene.frame_set(current_frame)