Catch those keymaps

Are you an addon developer? I have something to show you.

You may know Blender has a -b parameter that lets it run without a GUI. This can be used to render on servers, or in batches (like Render+ does).

What you may not know is that when Blender runs GUI-less the addons keyconfigs aren’t available and trying to access the keymaps raises an AttributeError.

Exception in module register(): '/home/januz/.config/blender/2.79/scripts/addons/XXXX.py'
Traceback (most recent call last):
  File "/home/januz/code/blender_RC/bin/2.79/scripts/modules/XXXX.py", line 350, in enable
    mod.register()
  File "/home/januz/.config/blender/2.79/scripts/addons/XXXX.py", line 1009, in register
    km = wm.keyconfigs.addon.keymaps.new(name='Object Mode', space_type='EMPTY')
AttributeError: 'NoneType' object has no attribute 'keymaps'

I have about five addons enabled now that spit this error. It’s harmless and doesn’t affect the render at all but it does fill the screen (and logs) very quickly making it harder to find important errors. Or maybe it just triggers my OCD :)

So if you are an addon writer, consider putting keymaps in a try block to catch that exception.

try:
    wm = bpy.context.window_manager
    km = wm.keyconfigs.addon.keymaps.new(name='Object Mode', space_type='EMPTY')

except AttributeError as e:
    if bpy.app.background:
        # Silence is golden
        pass
    else:
        # Not running in the background, something actually went wrong.
        # Re-raise the exception
        raise e
comments powered by Disqus
Share on Twitter Share on Reddit