To execute some actions at different stages of rendering, the developers have provided a set of handlers in the Blender Python API – special functions for handling events.
We can get all available handlers by executing the following command:
1 2 3 |
print(bpy.app.handlers) # bpy.app.handlers(frame_change_pre=[], frame_change_post=[], render_pre=[], render_post=[], ... ) |
The handlers that are directly related to the rendering process:
1 |
# on_render_init, on_render_pre, on_render_post, on_render_write, on_render_complete, on_render_cancel |
Each of these handlers is called at a certain moment, for example, the “on_render_init” handler is called when the render starts.
For the actions we need to be performed during the call to this handler, let’s define a function:
1 2 |
def on_render_init(*args): print('on redner init') |
In our example, it just prints a text to the console, but we can fill our function with actions whatever we need.
Bind our function to the handler call:
1 |
bpy.app.handlers.render_init.append(on_render_init) |
Now, every time at the beginning of the render, the text will be printed to the system console.
Let’s define similar functions for each render event:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
def on_render_pre(*args): print('on redner pre') def on_render_post(*args): print('on redner post') def on_render_write(*args): print('on render write') def on_render_complete(*args): print('on redner complete') def on_render_cancel(*args): print('on redner cancel') |
And link them with the corresponding handlers:
1 2 3 4 5 6 |
bpy.app.handlers.render_init.append(on_render_init) bpy.app.handlers.render_pre.append(on_render_pre) bpy.app.handlers.render_post.append(on_render_post) bpy.app.handlers.render_write.append(on_render_write) bpy.app.handlers.render_complete.append(on_render_complete) bpy.app.handlers.render_cancel.append(on_render_cancel) |
Now, when rendering, we will get the following output to the system console, for a two-frame animation:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
on redner init on redner pre Saved: 'C:\tmp\0001.png' Time: 00:00.32on render stats (Saving: 00:00.02) on redner post on render write on redner pre Saved: 'C:\tmp\0002.png' Time: 00:00.13on render stats (Saving: 00:00.02) on redner post on render write on redner complete |
As we can see, rendering events are handled in the following order:
- render_init – before rendering starts
- render_pre – before rendering of each frame
- render_post – after each frame has finished rendering
- render_write – after saving each frame
- render_complete – after all frames are rendered
The render_cancel event is fired when a render is canceled, for example, if the user presses the ESC button during a render.
This was a gem!!
Excellent explanation and exactly what I needed right now!