How to join objects with Python? I try to do this:

bpy.ops.object.select_all()
bpy.ops.object.join()


in my script. It selects all the stuff like CtrlA but fails on join() (CtrlJ) with the following error message:


  Traceback (most recent call last):   File "", line 1,
  in    File "C:\Program Files\Blender
  Foundation\Blender\2.71\scripts\modules\bpy\ops.py", line 188, in
  __ call __
      ret = op_call(self.idname_py(), None, kw) RuntimeError: Operator bpy.ops.object.join.poll() failed, context is incorrect


the message is from console.

How can I make this work?
CtrlA, CtrlJ actually works.
If you don't want to change the real selection states, you may wanna use an override:

import bpy

scene = bpy.context.scene

obs = []
for ob in scene.objects:
    # whatever objects you want to join...
    if ob.type == 'MESH':
        obs.append(ob)

ctx = bpy.context.copy()

# one of the objects to join
ctx['active_object'] = obs[0]

ctx['selected_objects'] = obs
# In Blender 2.8x this needs to be the following instead:
#ctx['selected_editable_objects'] = obs

# We need the scene bases as well for joining.
# Remove this line in Blender &gt;= 2.80!
ctx['selected_editable_bases'] = [scene.object_bases[ob.name] for ob in obs]

bpy.ops.object.join(ctx)