0
$\begingroup$

I'm calling Blender from the command line with blender --python script.py, and in that script I'm rendering the scene and saving as an image. I tried this:

import bpy

bpy.ops.render.render()
bpy.ops.image.save_as(filepath="render.png")

but this produces RuntimeError: Operator bpy.ops.image.save_as.poll() failed, context is incorrect. I believe the correct way to address this is to override the context as shown in an answer to a previous question of mine. Something like this:

import bpy

for area in bpy.context.screen.areas:
    if area.type == "IMAGE_EDITOR":
        image_editor = area
        break 
else:
    raise RuntimeError("IMAGE_EDITOR area not found")

with bpy.context.temp_override(area=image_editor):
    bpy.ops.render.render()
    bpy.ops.image.save_as(filepath="render.png")

But the image editor is not in bpy.context.screen.areas, so the RuntimeError is triggered. Any ideas on how to do this properly?

$\endgroup$

1 Answer 1

1
$\begingroup$

You can render straight from command line.

Or you could use the render operator with image saving. That's
bpy.ops.render.render(write_still=True). See the documentation

$\endgroup$
5
  • $\begingroup$ Thanks. How do I control where the image is saved when using write_still=True? $\endgroup$
    – wwww
    Oct 9, 2022 at 15:47
  • $\begingroup$ @wwww use the argument -o filepath it's described in the docs linked in the answer. :) $\endgroup$
    – Gorgious
    Oct 9, 2022 at 16:34
  • $\begingroup$ What I'm asking for is a way to set that in the script rather than the command line options. I'm hitting render multiple times with different output paths in the same script. $\endgroup$
    – wwww
    Oct 9, 2022 at 17:02
  • $\begingroup$ @wwww You can probably set up view layers, compositing, and other functionality to do what you need. Rendering is multithreaded and Python scripts might have issues with that if you are planning to render multiple times or do something immediately after rendering from a script. Might be better to modify the file, programmatically if needed, but then save and render separately. This is starting to sound a bit like an XY problem. I would suggest asking a separate question about the whole thing you are attempting to achieve and provide all the context. $\endgroup$ Oct 9, 2022 at 17:37
  • $\begingroup$ @MartynasŽiemys Fair enough, I'll accept your answer. $\endgroup$
    – wwww
    Oct 9, 2022 at 19:23

You must log in to answer this question.

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