Add driver using Python?

quick version: see the image

In short, I’m looking for correct way to use “driver_add (“path”, index)” to add driver to geometry node input.

Creating drivers in common modifiers are easy:

For example creating a driver at the width paramater of bevel modifier using the script below.

# Get the object and modifier
cube = bpy.data.objects["Cube"]
bevel_mod = cube.modifiers["Bevel"]

# Create a new driver for the Bevel modifier width parameter
driver = bevel_mod.driver_add("width").driver

However when facing geometry nodes, it does not work.

Because there is “[” after the modifier, rather than “.”:

GeometryNode Input path: bpy.data.objects["Cube"].modifiers["GeometryNodes"]["Input_2"]

Bevel Input path: bpy.data.objects["Cube"].modifiers["Bevel"].width

I can add driver manually to both modifiers by right click, but I have 88 objects to add driver to.

Hello !

That’s a bit tricky indeed :

bpy.context.selected_objects[0].driver_add(‘modifiers[“GN”][“Input_2”]’)

image

A common issue you can run into is to switch the " and the ’
if you write :

bpy.context.selected_objects[0].driver_add(“modifiers[‘GN’][‘Input_2’]”)

You’ll get an error :

Traceback (most recent call last):
File “<blender_console>”, line 1, in
TypeError: bpy_struct.driver_add(): property “modifiers[‘GN’][‘Input_2’]” not found

PS :
Just checked, in fact this works too :

bpy.context.selected_objects[0].modifiers[‘GN’].driver_add(‘[“Input_2”]’)

I probably mixed the " and ’ in my first test :smiley:

Have fun !

3 Likes