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:


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


I tried to reproduce this in the console, with:

bpy.context.space_data.context = 'WORLD'
bpy.data.node_groups["Shader Nodetree"].nodes["Gradient Texture"].gradient_type = 'EASING'  


and I got the following error:


  Traceback (most recent call last): 
  File "", line 1, in  KeyError: 'bpy_prop_collection[key]: key "Shader Nodetree" not found'


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
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

#create new gradient texture node
gradNode = nt.nodes.new(type="ShaderNodeTexGradient")

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

#Connect color out of Grad node to Color in of Background node
gradColOut = gradNode.outputs['Color']
backColIn = backNode.inputs['Color']
nt.links.new(gradColOut, backColIn)

#set gradient type to easing
gradNode.gradient_type = 'EASING'