3
$\begingroup$

Sometime when writing a python script I will run into an error such as syntax or some Exceptions. The script will partially execute, but not everything. This is frustrating because I have to manually undo what the script executed before I can run the script again. Is there a way that I can have the script undo what it has done if it fails. I want the script to only make permanent changes if it ran without error.

$\endgroup$
4
$\begingroup$

You could enable Undo support for your operator. Below

bl_label = "Simple Object Operator"

add

bl_options = {'REGISTER', 'UNDO'}

But I wouldn't make the operator undo itself on errors, rather let the user do it if necessarily. However, your script shouldn't raise exceptions in the first place, but check in the operator's poll() classmethod, if all pre-conditions are met. Or let it return {'CANCELLED'} inside the execute() body before something is damaged.

| improve this answer | |
$\endgroup$
3
$\begingroup$

Wrap your script in an operator. You will only need one undo step then. Just replace the main function of this (shortened) template from Text Editor -> Python -> Operator Simple

import bpy

def main(context):
    #your script here
    pass

class SimpleOperator(bpy.types.Operator):
    bl_idname = "object.simple_operator"
    bl_label = "Simple Object Operator"

    def execute(self, context):
        main(context)
        return {'FINISHED'}

bpy.utils.register_class(SimpleOperator)
try:
    bpy.ops.object.simple_operator()
except Exception as e:
    print("something went wrong")
    #raise the exception again
    raise e

(See CoDeman's post). Using blender's undo system with bpy.ops.ed.undo is rather unreliable.

You may:

  • check if requirements are met before performing your actions
  • save some data with python and restore it if an error occured
  • write a backup to disk and load it if an error occurred
| improve this answer | |
$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.