Sub topic 14
Scripting renders with Python
This chapter assumes you have read the earlier chapters on Output properties, still renders, image sequences and FFmpeg video. It also assumes you can run Blender from a terminal and read basic Python. Here you will turn those settings into a script that renders reliably, can be repeated, and reports problems.
What a render script does
Every setting you changed in the Properties editor is a property in the bpy module, so a render script does three things:
- Check that the scene can render.
- Assign the properties you would otherwise set by hand.
- Call the render operator,
bpy.ops.render.render.
flowchart TD
A[Start Blender with script] --> B[Read arguments after --]
B --> C{Camera and paths valid?}
C -- no --> D[Raise error, exit code 1]
C -- yes --> E[Set engine, resolution, output]
E --> F{Mode}
F -- still --> G[frame_set, render write_still]
F -- video --> H[Set range and FFmpeg, render animation]
G --> I[Files on disk]
H --> IThe block above is only a flowchart. In the chapter format, a diagram needs the diagram mermaid fence, so here it is in that form:
Properties you will set most often
| Goal | Property | Example value |
|---|---|---|
| Engine | `scene.render.engine` | `'CYCLES'` |
| Samples | `scene.cycles.samples` | `128` |
| Denoising | `scene.cycles.use_denoising` | `True` |
| Resolution | `scene.render.resolution_x`, `resolution_y` | `1920`, `1080` |
| Scale | `scene.render.resolution_percentage` | `100` |
| Frame range | `scene.frame_start`, `scene.frame_end` | `1`, `120` |
| Frame rate | `scene.render.fps` | `24` |
| Image format | `scene.render.image_settings.file_format` | `'PNG'` |
| Output path | `scene.render.filepath` | `'//renders/still.png'` |
| Camera | `scene.camera` | a camera object |
Engine identifiers vary between Blender versions. Cycles is always 'CYCLES' and Workbench is 'BLENDER_WORKBENCH'. EEVEE was 'BLENDER_EEVEE', became 'BLENDER_EEVEE_NEXT' in Blender 4.2, and returned to 'BLENDER_EEVEE' in 5.0. If you assign an identifier your version does not have, Python raises a TypeError that lists the valid values.
The render operator
bpy.ops.render.render has two modes that matter here:
write_still=Truerenders the current frame and saves it toscene.render.filepath. Without it, the image exists only in the "Render Result" buffer in memory and is never written.animation=Truerenders every frame fromframe_starttoframe_endand writes each one as it finishes.
The call blocks until rendering ends. In a background session that is what you want, because the script continues only after the files exist.
A complete job script
Save this as render_job.py. It takes its options from the command line, validates the scene, and renders either a still or an H.264 video.
import argparse
import sys
import bpy
def parse_args():
# Blender ignores everything after "--", so the script reads it itself.
argv = sys.argv[sys.argv.index("--") + 1:] if "--" in sys.argv else []
parser = argparse.ArgumentParser(prog="render_job.py")
parser.add_argument("--mode", choices=["still", "video"], required=True)
parser.add_argument("--frame", type=int, default=1)
parser.add_argument("--start", type=int, default=1)
parser.add_argument("--end", type=int, default=48)
parser.add_argument("--out", default="//renders/out")
return parser.parse_args(argv)
def check_scene(scene, out):
if scene.camera is None:
raise RuntimeError(f"Scene '{scene.name}' has no active camera")
if out.startswith("//") and not bpy.data.filepath:
raise RuntimeError("Save the .blend file first: '//' paths need it")
def main():
args = parse_args()
scene = bpy.context.scene
check_scene(scene, args.out)
scene.render.resolution_x = 1920
scene.render.resolution_y = 1080
scene.render.resolution_percentage = 100
scene.render.filepath = args.out
if args.mode == "still":
scene.render.image_settings.file_format = "PNG"
scene.frame_set(args.frame)
bpy.ops.render.render(write_still=True)
else:
scene.frame_start = args.start
scene.frame_end = args.end
scene.render.fps = 24
scene.render.image_settings.file_format = "FFMPEG"
scene.render.ffmpeg.format = "MPEG4"
scene.render.ffmpeg.codec = "H264"
scene.render.ffmpeg.constant_rate_factor = "MEDIUM"
scene.render.ffmpeg.audio_codec = "NONE"
bpy.ops.render.render(animation=True)
main()Run it in the background:
blender -b scene.blend --python render_job.py --python-exit-code 1 -- --mode still --frame 10 --out //renders/shot
blender -b scene.blend --python render_job.py --python-exit-code 1 -- --mode video --start 1 --end 48 --out //renders/clip_Several details in this command matter:
- Put the
.blendfile first so it loads before the script runs. --python-exit-code 1makes Blender exit with status 1 when the script raises an exception. Without it, a failed script can still end with exit status 0, and a build system will think the job worked.- Everything after the bare
--belongs to your script.
Choosing the frame for a still
Set the frame with scene.frame_set(n), not by assigning scene.frame_current = n. frame_set also re-evaluates animation, so objects and drivers are in the right state when rendering starts. Assigning the property alone can leave some evaluated data stale.
Output paths and file names
Path rules in a script match the interface:
- A path starting with
//is relative to the saved.blendfile. In an unsaved file it has no valid base, which is why the script checksbpy.data.filepath. - For a still, Blender adds the extension (
.png) unlessscene.render.use_file_extensionisFalse. - For an image sequence,
#characters set the frame-number padding, so//renders/frame_####producesframe_0001.png. If the path has no#, Blender appends the frame number itself. - For FFmpeg output, the path names one video file, and Blender adds
.mp4or the matching extension. Using//renders/clip_gives a file such asclip_0001-0048.mp4.
To resume an interrupted image-sequence render, set scene.render.use_overwrite = False and scene.render.use_placeholder = True. Blender then skips frames that already exist and creates an empty placeholder file when it starts each frame. A second process can then work on the remaining frames. The placeholders do not apply to FFmpeg video, which is one file.
Looping over several renders
Because bpy.ops.render.render blocks, a plain loop gives you a batch. This example renders a still from every camera in the scene:
import bpy
scene = bpy.context.scene
original_camera = scene.camera
for cam in [o for o in scene.objects if o.type == "CAMERA"]:
scene.camera = cam
scene.render.filepath = f"//renders/{cam.name}"
bpy.ops.render.render(write_still=True)
scene.camera = original_cameraReset anything you change when the loop ends, especially if you run the script inside the interface and keep working in the same file.
Reacting to render events with handlers
Blender calls functions you register in bpy.app.handlers at set points in a render. The useful lists are render_init, render_pre, render_post, render_write, render_complete and render_cancel.
import bpy
from bpy.app.handlers import persistent
@persistent
def on_frame_done(scene, *args):
print(f"Finished frame {scene.frame_current}")
@persistent
def on_all_done(scene, *args):
print("Render complete")
bpy.app.handlers.render_post.append(on_frame_done)
bpy.app.handlers.render_complete.append(on_all_done)Two points keep handlers safe:
- Accept
sceneplus*args, because the exact arguments differ between lists and versions. - Do not append the same function twice. If you rerun a script in the Text editor, remove the old function first with
bpy.app.handlers.render_post.remove(on_frame_done), or guard the append withif on_frame_done not in bpy.app.handlers.render_post:. Otherwise each frame prints several times.
Saving the Render Result yourself
After a render, the image is in bpy.data.images["Render Result"]. You can save it under a different name or format without changing the scene's output settings:
import bpy
bpy.ops.render.render()
bpy.data.images["Render Result"].save_render(
filepath=bpy.path.abspath("//renders/preview.jpg")
)save_render does not resolve //, so wrap the path in bpy.path.abspath. It uses the scene's image settings unless you pass a different scene argument. It saves only the most recent still, so use it after a single-frame render.
Common scripting errors
- "No camera found in scene":
scene.cameraisNone. Set it or fail early, ascheck_scenedoes. - Nothing written after a still render:
write_still=Truewas missing. - Wrong scene rendered:
bpy.context.sceneis the active scene. In a file with several scenes, passscene="SceneName"to the render operator, or switch the active scene inbpy.context.window.scene. - Overwritten output: two jobs wrote to the same
filepath. Put the job name or frame range in the path. - A
TypeErroron an enum: the value does not exist in your Blender version. Read the list in the error message. - Script works in the UI but not in background mode: operators that depend on a window or area may lack context. The render operator is fine in background mode, but other
bpy.opscalls may not be.
Exercises
Exercise
A script sets scene.render.filepath = '//renders/shot' and calls bpy.ops.render.render(), then the renders folder is empty. What is missing, and how should the call change to save a still?
Show answer
The call lacks writestill=True, so the image stays only in the Render Result buffer. Use bpy.ops.render.render(writestill=True). Also check that the .blend file has been saved, so that '//' resolves to a real folder.
Exercise
Write the command that runs renderjob.py on scene.blend in the background, renders frames 10 to 30 as a video to //renders/test, and makes Blender exit with status 1 if the script fails.
Show answer
blender -b scene.blend --python renderjob.py --python-exit-code 1 -- --mode video --start 10 --end 30 --out //renders/test