Create a blender scene in python

Using blender, I need to test multiple settings for my painting references e.g. lighting, material or the complete location. It all started with that minimal working example to render the sphere above.

# /tmp/blender/blender_mini_example.py
import bpy
import time
import os
# Initialize variables used to print the rendered picture
dir_path = os.path.dirname(os.path.realpath(__file__))
filename = str(int(time.time())) + '.render' + '.png'
# Delete the default cube
objs = bpy.data.objects
objs.remove(objs["Cube"], do_unlink=True)
# Add a sphere
bpy.ops.mesh.primitive_uv_sphere_add(location=(-3, 0, 0))
# Render
bpy.context.scene.render.filepath = filename
bpy.ops.render.render(write_still=True)
# Print directory path and filename
print(dir_path+"/"+filename)

I’ve added line 7 in order to get rid of unneeded addons-on and their accompanying exceptions.

1
2
3
4
5
6
7
cd /tmp/blender
rm *.png
blender \
    --background \
    --python blender_mini_example.py \
    --verbose 0 \
    --factory-startup
Blender 2.93.6 (hash c842a90e2fa1 built 2021-11-17 16:06:39)
/run/user/1000/gvfs/ non-existent directory
Fra:1 Mem:88.84M (Peak 89.51M) | Time:00:00.14 | Syncing Light
Fra:1 Mem:88.84M (Peak 89.51M) | Time:00:00.14 | Syncing Camera
Fra:1 Mem:88.84M (Peak 89.51M) | Time:00:00.14 | Syncing Sphere
Fra:1 Mem:89.25M (Peak 89.54M) | Time:00:00.20 | Rendering 1 / 64 samples
Fra:1 Mem:89.20M (Peak 89.54M) | Time:00:01.24 | Rendering 26 / 64 samples
Fra:1 Mem:89.20M (Peak 89.54M) | Time:00:02.02 | Rendering 51 / 64 samples
Fra:1 Mem:89.20M (Peak 89.54M) | Time:00:02.43 | Rendering 64 / 64 samples
Saved: '1639292187.render.png'
 Time: 00:03.13 (Saving: 00:00.61)

/tmp/blender/1639292187.render.png

Blender quit