Why doesn't this work?

This fails to run. I don’t get it, but then again, I’m very new to bpy. I created the simple script below mostly by copying the various commands in the info view. The line that causes the script to fail is copied verbatim from the info view.

import bpy


bpy.ops.object.modifier_add(type='SUBSURF')
bpy.context.object.modifiers[-1].name = "mysubsurf"
bpy.context.object.modifiers("mysubsurf").levels = 2
bpy.ops.object.modifier_apply(apply_as='DATA', modifier='mysubsurf')

The line that fails is bpy.context.object.modifiers(“mysubsurf”).levels = 2
The only error in the info view is

Python script fail, look in the console for now…

Using Blender 2.76 in windows 7 on a Mac Pro.

edit: What console is it talking about? The Python Console shows no error info.

There is a function called “Toggle System Console”, you can search for it in the search function in 3d view. When activated once! a cmd window will be activated for blender (alt-tab might be req.). It will usually display errors occuring during script execution (python console will display compiling errors).

On a second note, in row 2 & 3 you are not accessing an object. I assume you want to access the active_object :


bpy.context.object.active_object.modifiers[0].name = "mysubsurf" #Never use -1 for accesing in a list/collection!!!!!!
bpy.context.object.active_object.modifiers.get("mysubsurf") #Use get() if you want to access with the name!

Line 1 & 4 you call specific operators on a context, and that context is by default the active object.
However i would suggest creating the modifier through the object aswell and also using the context passed to the script (using bpy.context is usually the same context but it might not be!):


mod = context.active_object.modifiers.new("name", 'SUBSURF')
mod.levels = 2
bpy.objects.modifier_apply(apply_as='DATA', modifier="name") 

This way you get an modifier object returned when calling new() which you can use to assign all values to. When calling operators you only get a return statement if the operator ‘Finished’ execution or ‘Cancelled’.

Hope this helps probably went overboard with the explanation :slight_smile: !

try this:

import bpy

ob = bpy.context.active_object

ob.modifiers.new(name='mysubsurf', type='SUBSURF')
ob.modifiers["mysubsurf"].levels = 2
bpy.ops.object.modifier_apply(apply_as='DATA', modifier="mysubsurf")


Thank you Osares and Albertofx. You have shed some light on my quest. I watched a bit of a video tutorial on blender cookie that recommended reading the results from the info window and typing it into your script which actually worked for me on real world script that I was trying to create. I guess I was more curious how copying the results from info wouldn’t work.

What I should have really been worrying about is how to access the objects properly.