# How to refresh workspace

I do these operations in a for loop:

1. Selecting all objects
2. Remove
5. Bind cameras to model
7. Render

The problem is how to refresh the entire scene for next iteration? I have tried to load a fresh file using bpy.ops.wm.open_mainfile, but it causes an error. It seems that the entire project including the script loads again. So, I tried to remove objects in bpy.data.objects but I noted that there are bpy.data.cameras and bpy.data.lamps which should be also removed. What is the correct way to do this job? Does selecting all objects and deleting them makes the trick? Note that there is an animation along with cameras, lamps, etc.

The solution is to delete data collections. There are plenty of collections in bpy.data which are not cleaned after deleting the object. For example if you add a camera, an entry in bpy.data.camera would be added but after deleting the camera object that entry remains that finally leads to out of memory errors. So the solution would be some thing like this:

def clear_collection(collection):
for item in collection:
collection.remove(item, True)

def cleanup():
clear_collection(bpy.data.actions)
clear_collection(bpy.data.armatures)
clear_collection(bpy.data.brushes)
clear_collection(bpy.data.cameras)
clear_collection(bpy.data.groups)
clear_collection(bpy.data.images)
clear_collection(bpy.data.lamps)
clear_collection(bpy.data.materials)
clear_collection(bpy.data.meshes)
clear_collection(bpy.data.objects)
clear_collection(bpy.data.textures)

cleanup()