# How to set a background using the cycles render engine with the API

I'm just getting started with the Blender API, and I'm trying to set the background texture using the API.

In the GUI, I do the following:

1. Choose the Cycles render engine bpy.context.scene.render.engine = 'CYCLES'
2. Press the World context button,
3. In the Surface menu, press Use nodes,
4. In the Surface box, Background,
5. In the Color box select Gradient Texture,
6. In the box below that select Easing,

I tried to reproduce this in the console, with:

bpy.context.space_data.context = 'WORLD'


and I got the following error:

Traceback (most recent call last):

I spent over an hour reading the doc and Googling, but I still can't do this in my script? Really appreciate any advice how to do this programatically/in a headless script?

Thanks

• – p2or Jun 20 '15 at 19:30
• Hi poor, thank you very much for the link, it helped a lot. – Ajay T Jun 21 '15 at 10:25

When you select the Gradient option for the Color item in the World Panel, it runs a number of calls to create the Gradient node and route its socket to the color input of the Background node.

To replicate that process, you can't just call the panel tool that you clicked on. I believe you have to manually add the gradient node to the World nodetree and connect the node to the background node via python.

import bpy

scn = bpy.context.scene
scn.render.engine = 'CYCLES'
scn.world.use_nodes = True

#select world node tree
wd = scn.world
nt = bpy.data.worlds[wd.name].node_tree

#find location of Background node and position Grad node to the left
backNode = nt.nodes['Background']