How to set the render-output using arbitrary values? When rendering, it can be useful to automate setting the output file path using existing data from within the blend file.

Is it possible to use variables in the render output path? eg,

//$(file)_$(scene)_$(camera)_####.png

Either from the interface or the command-line.



Note, this question is similar to How to show render-stamp for arbitrary values?
While Blender has no build-in support for this feature. You can do this using Python:

From Within Blender

Add a script into your file, call it render_path.py (for example).


Press Run Script (only need to do once)
Enable the Register option in the text editor (so it runs automatically).


Here is a sample script.

import bpy

def render_filepath_set(scene):
    scene.render.filepath = '{file}_{scene}_{camera}_####'.format(
            file=bpy.data.filepath.rpartition('.')[0],
            scene=scene.name,
            camera=scene.camera.name,
            )

bpy.app.handlers.render_init.append(render_filepath_set)


From the Command-Line

A similar method can be used, by running a script from the command line, first create a file.

render_path.py

import bpy
scene = bpy.context.scene
scene.render.filepath = '{file}_{scene}_{camera}_####'.format(
        file=bpy.data.filepath.rpartition('.')[0],
        scene=scene.name,
        camera=scene.camera.name,
        )


And run it with:

blender --background /d/untitled.blend --python render_path.py --render-anim


Or, you can avoid using a Python file and simply pass in the script on the command line (using --python-expr).

blender --background /d/untitled.blend --python-expr "import bpy; scene = bpy.context.scene; scene.render.filepath = '{file}_{scene}_{camera}_####'.format(file=bpy.data.filepath.rpartition('.')[0], scene=scene.name, camera=scene.camera.name)"


This isn't practical to manually type in of course, but can be used when running Blender as an automated task (shell script / bat file... etc).