The python path to the links between each node is
bpy.data.materials[].node_tree.nodes[].inputs[].links[].from_node
So for each material we want to start at the Material Output node then loop through each array of inputs[]
and links[]
to move through the connections. Going this way (using from_node) there should only be one link for each input, but if you want to reverse the order (by using to_node) you can have multiple links for each output.
import bpy
def followLinks(node_in):
for n_inputs in node_in.inputs:
for node_links in n_inputs.links:
print("going to " + node_links.from_node.name)
followLinks(node_links.from_node)
for mat in bpy.data.materials:
print("Traversing " + mat.name)
for mat_node in mat.node_tree.nodes:
if mat_node.type == 'OUTPUT_MATERIAL':
# we start at the material output node
print("Starting at " + mat_node.name)
followLinks(mat_node)