# How can I change the color of a material using Python script?

I'm modeling LED signs with different frequencies and duty cycles to animate flickering LEDs. It is impractical to manually set the color of LEDs at all the keyframes for each single LED, since I have more than 20 LEDs and they all have different frequencies & duty cycles. I think it will be so much easier to use Python script. Here is the description of the problem.

Use the pictures above as an example. I created an object and emission shader "material 1" manually. "Material 1" only applies to the circle in the middle of this object (as shown in (a)).

I want the color of material 1 to be red from frame 1 to frame 10. From frame 11 to 30, the color will be black(as shown in (b)). From frame 31 to 40, the color turns to red again, then black from frame 41 to 60. As you can see from the first picture, the same pattern happens over and over again and continues to the last frame.

I was wondering if I could use Python script to simulate this instead of manually set keyframes for all the LEDs. Thank you all in advance for your responses.

This is related: Control Cycles material nodes and material properties in Python

This is how you add an keyframe:

import bpy
# get the material
mat = bpy.data.materials['Material_Name']
# get the nodes
nodes = mat.node_tree.nodes
# get some specific node:
# returns None if the node does not exist
emission = nodes.get("Emission")
# set strength to 0.8
emission.inputs[1].default_value = 0.8
# add keyframe to strength at frame 1
emission.inputs[1].keyframe_insert("default_value", frame=1)
# set strength to 0
emission.inputs[1].default_value = 0
# add keyframe to strength at frame 21
emission.inputs[1].keyframe_insert("default_value", frame=21)


Now the intensity will animate from 0.8 to 0 in 20 frames