How can I apply a basic material to an object using python in cycles render? [duplicate]

I would like to be able to apply and edit a material to objects I have create using python script. I am using the cycles render engine but can't find a way to get this to work.

I've tried a bunch of the answers already given in other threads but none of them seem to work.

I would like to: create and apply a new material for each object and adjust the colours using rgb, using nodes or otherwise.

Sorry if this is a stupid question, I'm very new to blender scripting!

• Please add details as to what you have tried and at what point it doesn't work. – Ray Mairlot Aug 7 '15 at 10:59

The super-simple example is

import bpy

def mission1(obj):
mat = bpy.data.materials.new("bacon")
mat.diffuse_color=(0.8,0,1)

obj.data.materials[0] = mat

obj = bpy.context.active_object
mission1(obj)


If you need to actually create and rig nodes, update your question with a screenshot of nodes you have manually created and if I have time I'll cobble together some code to build a matching node tree using python.