3
$\begingroup$

I am wondering whether it is possible to run a Python script in Blender 2.82 from the text editor, such that each time the script is run, it reverses everything that was done in the previous run. In other words, if I first run the script from the default home file, then each time I run the code, the result will be the exactly same as if I had manually created a new Blender document and run the code there.

A minimum working example is as follows:

import bpy
#Some code here to delete everything
bpy.ops.mesh.primitive_cylinder_add(vertices = 360, radius = 1, depth = 1)
bpy.ops.curve.primitive_bezier_circle_add(radius = 2)

I have tried putting the following codes in the commented line, but none of these solutions are satisfactory:

  1. Nothing — A new mesh and Bézier curve is generated each time the code is run.
  2. bpy.ops.wm.read_homefile(use_empty=True) — This closes the Blender window without running the code.
  3. The following code:
for o in bpy.data.objects:
    bpy.ops.object.delete()

— A new mesh for the cylinder and a curve for the Bézier circle are still generated each time the code is run.

  1. Same as above, with the following additional lines:
for o in bpy.data.curves:
    bpy.ops.curve.delete()

— This leads to an runtime error: ‘Operator bpy.ops.curve.delete.poll() failed, context is incorrect’. In any event, if possible, it would be preferable to have a solution that is not specific to a particular kind of object (eg curves), but works regardless of what might happen to be in the scene.

  1. bpy.ops.scene.new() — This runs the script in a blank scene, which is the desired effect. However, I have been struggling to find a method to delete all other scenes with their content.

Any help would be much appreciated.

$\endgroup$

1 Answer 1

0
$\begingroup$

Maybe try this code:

def reset_blend():
    bpy.ops.wm.read_factory_settings()

    for scene in bpy.data.scenes:
        for obj in scene.objects:
            scene.objects.unlink(obj)

    # only worry about data in the startup scene
    for bpy_data_iter in (
            bpy.data.objects,
            bpy.data.meshes,
            bpy.data.lamps,
            bpy.data.cameras,
    ):
        for id_data in bpy_data_iter:
            bpy_data_iter.remove(id_data)

reset_blend()
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .