I am creating a Python script that bakes the textures for each object in the scene, and then deletes all the shader nodes of the materials of each object and replaces them with image texture nodes of the baked diffuse and roughness maps. However, I've noticed that, after running the program, all of the image texture nodes have been replaced with the baked maps of only the last object and the baked maps of the other objects have vanished. 

This is the code that creates the images that get baked onto

    def bakeObj(obj, dest, img_size):
        obj.select_set(True)
        bpy.context.view_layer.objects.active = obj 

        imgDiffuse = bpy.data.images.new(obj.name + '_Diffuse',img_size,img_size) 
        imgRough = bpy.data.images.new(obj.name + '_Rough',img_size,img_size) 

In between I bake the textures of the object onto imgDiffuse and imgRough. Then this is the code for the assignment of the images.

    for mat in obj.data.materials:
        print(mat.name)
        mat.use_nodes = True
        nodes = mat.node_tree.nodes
        
        # delete nodes 
        for n in mat.node_tree.nodes: 
            excludedNodes = {'Principled BSDF','Material Output'}
            if n.name not in excludedNodes:
                mat.node_tree.nodes.remove(n)

    
        diffuse_node = nodes.new('ShaderNodeTexImage')
        diffuse_node.name = 'Diffuse_node'
        diffuse_node.image = imgDiffuse
        
        rough_node = nodes.new('ShaderNodeTexImage')
        rough_node.name = 'Rough_node'
        rough_node.image = imgRough
        
        # stick baked texture in material
        principled_bsdf_node = mat.node_tree.nodes["Principled BSDF"]
        links = mat.node_tree.links
        links.new(principled_bsdf_node.inputs[0], diffuse_node.outputs[0])
        links.new(principled_bsdf_node.inputs[9], rough_node.outputs[0])

For a more detailed illustration of the issue, see the images below. This is the setup of the objects. The highlighted material "shader_crustacean" should have been assigned the texture files corresponding to its parent object "crustacean(1, 1).parts(0, factory=LobsterBodyFactory)" 

[![enter image description here][1]][1]

Instead, it has the texture files corresponding to the last object "crustacean(1,1).parts(10).extra(BezierCurve.015, 10)". The same occurs for all other materials.

[![enter image description here][2]][2]

Meanwhile, the image dropdown menu seems to show that all the other files have actually disappeared or were overwritten somehow.

[![enter image description here][3]][3]

It seems that the last call of the function somehow causes all the other textures to get destroyed. Is this some kind of memory overwriting issue or weird bug with blender? For reference, this is all being run in headless mode.

  [1]: https://i.sstatic.net/OqR3h.png
  [2]: https://i.sstatic.net/yTzuU.png
  [3]: https://i.sstatic.net/wgqe3.png