Blender as a module: no bpy.context.window

I built blender as a module and it works well. The intent is to make a headless renderer and it works as expected when I run my scripts from python directly. But when I run my scripts from a task queue manager like huey I get all sorts of unexpected behavior.
I noticed that it crashes outright when issueing bpy.ops.wm.open_mainfile(filepath=render_base_file).

In my case it is not a terrible issue as I need to import a mesh, however I did set it up so that I can set base materials, a world and render settings for different render engines in these ‘render_base_files’ so I could have drop-in ‘looks’.
So I set out to append the world, the materials and the scene from the base file and it works fine:

def append_scene(filepath):
    with, link=False) as (data_from, data_to):
        data_to.scenes = [data_from.scenes[0]]
    bpy.context.window.scene =[0]
    print("scenes: {}".format([sc for sc in]))
    print("default scene: {}".format(

def append_materials(filepath):
    with, link=False) as (data_from, data_to):
        data_to.materials = [m for m in data_from.materials]
        data_to.worlds = [m for m in data_from.worlds] =[0]

It appends the data, but it appears that I cannot change the default scene (which holds the render settings) because bpy.context.window does not exist.

This seems to me to be a source of all manner of unexpected behavior. First of all, bpy.context.window exists when one opens a python prompt and :

Python 3.7.4 (default, Aug 13 2019, 20:35:49)
Type 'copyright', 'credits' or 'license' for more information
IPython 7.19.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: import bpy

In [2]: bpy.context.window
Out[2]: <bpy_struct, Window at 0x55796538f848>

In [3]:

But in Huey:

  File "/Projects/ActiveProjects/163-vabi/scratchpad/huey-render/", line 80, in create_scene
  File "/Projects/scratchpad/huey-render/", line 53, in append_scene
    bpy.context.window.scene =[0]
AttributeError: 'NoneType' object has no attribute 'scene'

Any tips or hints for this issue ?

thx Sander

I tried celery, and that one already stalls on importing the geometry json, on account of me needing pythonnet. I could look at Django-Q…

huey and celery are thread queue-ers and managers and I realized that there is no reason to assume that bpy is thread-safe, which results in all manner of unexpected behavior.
This problem can be solved by moving the bpy import into the threaded function:

def my_function():
    import bpy
    res = bpy.ops.wm.open_mainfile(filepath="testfile.blend") # this segfaults when bpy import is outside of the thread.