'context' error when trying to bevel an object with Python I need some code to do Bevel-operation within a Python script. Ultimately I need a series of blocks (32) in different sizes and in which each is bevelled on one side to be exported as STL-file for use on a 3D-printer. So I tried to start bevelling a while object to start with, I used the default cube to experiment. Bevelling it manually showed me some interesting API commands in the Blender Info window, which I copied to the Scripting module, but running it brings me into trouble. My first guess was something like this:

# generate the cube and make it selected and active:
import bpy
bpy.ops.mesh.primitive_cube_add(radius=1)
myobject = bpy.context.active_object
print("myobject: ", myobject)
myobject.select = True
bpy.context.scene.objects.active = myobject

# This is copied from the Info window:
bpy.context.space_data.context = 'MODIFIER'
bpy.ops.object.modifier_add(type='BEVEL')
bpy.context.object.modifiers["Bevel"].width = 0.2
bpy.context.object.modifiers["Bevel"].segments = 5
bpy.context.object.modifiers["Bevel"].profile = 0.7
bpy.context.object.modifiers["Bevel"].material = -1
bpy.ops.object.modifier_apply(apply_as='DATA', modifier="Bevel")

# Manually the bevel is done at this point!


But when running the script it fails at the MODIFIER line:


  myobject:   Traceback (most recent call last): File "/Text", line 10, in  AttributeError:
  
  'SpaceTextEditor' object has no attribute 'context' Error: Python
  
  script fail, look in the console for now...


Searching through the data objects and Googling hints me that I'm working with a wrong starting point, but how can this (bevel the cube)  be done easily?

Does someone have a simple example to share with me?

P.S. I use Blender 2.78, latest release.
You should avoid using ops when possible, see here. As for you code:

import bpy

# generate the cube and make it selected and active:
verts = [(-1.0, -1.0, -1.0), (-1.0, -1.0, 1.0), 
    (-1.0, 1.0, -1.0), (-1.0, 1.0, 1.0), (1.0, -1.0, -1.0),
    (1.0, -1.0, 1.0), (1.0, 1.0, -1.0), (1.0, 1.0, 1.0)]

faces = [(0, 1, 3, 2), (2, 3, 7, 6), 
        (6, 7, 5, 4), (4, 5, 1, 0),
        (2, 6, 4, 0), (7, 3, 1, 5)]

me = bpy.data.meshes.new('Cube')
ob = bpy.data.objects.new('Cube', me)
bpy.context.scene.objects.link(ob)
ob.select = True
bpy.context.scene.objects.active = ob
me.from_pydata(verts, [], faces)
me.update() 

# bevel the cube
bevel_mod = ob.modifiers.new('Bevel', 'BEVEL')
bevel_mod.width = 0.2
bevel_mod.segments = 5
bevel_mod.profile = 0.7
bevel_mod.material = -1
# we use ops here since there is really no other way
bpy.ops.object.modifier_apply(apply_as='DATA', modifier=bevel_mod.name)