5
$\begingroup$

I want to append a group with the Python API, like I would normally do with File > append.

I already tested this solution: How to Link/Append a data-block using the Python API?, and this one: How to link/append with a Python script?.

When I use bpy.ops.wm.append() blender crashes, I don't know why (the path is valid because I can link objects with the second method).

When I use bpy.data.libraries.load() I can't find how to import a whole group (not a dupli-group).

By importing a group I mean append all the objects in the group by keeping their relations.

$\endgroup$
2
$\begingroup$

The code in the first answer you linked handles the data retrieval exactly as you want it (if you set the link flag to False, but it later on always instantiates the result. In plain English: The group you're looking for has been appended just fine, but it only exists within bpy.data so far, it is not connected to your scene yet. Just as with linked data, you can instantiate such a group. But if you want to instead link the objects to your current scene as well (which what the append command does by default), then you have to modify the lower part of the code a little:

import bpy

filepath = "//Source.blend"
group_name = "Test"
# link = False means append, link = True will link the group
link = False 

# append the group defined in group_name from the .blend file
with bpy.data.libraries.load(filepath, link=link) as (data_src, data_dst):
    ## all groups
    # data_to.groups = data_from.groups

    # only append a single group we already know the name of
    data_dst.groups = [group_name]

    # link the objects contained in the group to your current scene
    # otherwise you won't ever see them!
for o in data_dst.groups[0].objects:
    bpy.context.scene.objects.link(o)

    # for safety measures, update the scene
    # most likely only necessary from within an add-on
bpy.context.scene.update()

The example above appends a group called Test from a file called Source.blend located in the same folder as the file you're working in right now.

The operators around bpy.data.libraries.xxx are low-level functions. The benefit of that is they execute really fast, and you have nice access to the retrieved data later on via the data_dst variable, which contains a bunch of lists with the stuff you retrieved. The downside is that a low level function really only does this one task. What the coder decides to do with the retrieved data is totally up to him, that's why you manually need to link the objects to the scene.

You can read more about the topic on the API pages: https://docs.blender.org/api/blender_python_api_2_78_0/bpy.types.BlendDataLibraries.html?highlight=libraries#bpy.types.BlendDataLibraries.load

$\endgroup$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.