How do I delete unused nodes in shader editor with python

Greetings, Community. I created a script that deletes all other nodes in the Shader editor that are not connected to the material output using the node wrangler

bpy.context.area.ui_type = ‘ShaderNodeTree’
bpy.ops.node.nw_del_unused()
bpy.context.area.ui_type = ‘TEXT_EDITOR’

But my issue is that the first time I run it, my tab switches to the shader editor and then writes an error. But when I return to the text editor and run the script once more, everything is fine.

What could be the issue. Why that error the first time?

Welcome to BA :slight_smile:

Your error is because your context is wrong, and your need to override it. I see you’ve already tried to do so, but your implementation isn’t quite right. See this to learn the right way:

Thank you for your response. Let me check it out

I checked the link sent, but after I replaced the necessary parameters, I am still encountering an error. Here is the code

import bpy

override_context = bpy.context.copy()
area = [area for area in bpy.context.screen.areas if area.type == “ShaderNodeTree”][0]
override_context[‘window’] = bpy.context.window
override_context[‘screen’] = bpy.context.screen
override_context[‘area’] = area
override_context[‘region’] = area.regions[-1]
override_context[‘scene’] = bpy.context.scene
override_context[‘space_data’] = area.spaces.active

bpy.ops.node.nw_del_unused(override_context)

Please am I wrong somewhere? I just want to delete unused nodes in shader editor using node wrangler. Or if there is any other way this can be done through python, I’m open to it. Thank you.

What’s the text of the error?

It says

IndexError: list index out of range

Ok so we know your context override is working :slight_smile: this is an entirely different error. Which line is giving this error?

area = [area for area in bpy.context.screen.areas if area.type == “ShaderNodeTree”][0]

This line is giving the error

Ok I think I know why, your “ShaderNodeTree” isn’t a valid type. You want “ NODE_EDITOR” - see:
https://docs.blender.org/api/current/bpy.types.Area.html#bpy.types.Area.type
Switch that out and it should work

Thank you so much!!!. This worked Perfectly

import bpy

override_context = bpy.context.copy()
area = [area for area in bpy.context.screen.areas if area.type == “NODE_EDITOR”][0]
override_context[‘window’] = bpy.context.window
override_context[‘screen’] = bpy.context.screen
override_context[‘area’] = area
override_context[‘region’] = area.regions[-1]
override_context[‘scene’] = bpy.context.scene
override_context[‘space_data’] = area.spaces.active

bpy.ops.node.nw_del_unused(override_context)

My day is made

1 Like

awesome, glad I could help :slight_smile: