Changing keymap on startup

Hi folks!

Using startup folder we can run scripts when Blender starts.
Using this I can change User Preferences and tweak overlay, render and other settings.
But how I can manage to modify keymap?

Here is the part of script:

import bpy
from bpy.app.handlers import persistent


@persistent
def init_preferences(dummy):
    kc = bpy.context.window_manager.keyconfigs['blender']

    """ 3D View """
    view_3d_ki = kc.keymaps['3D View'].keymap_items

    # Set 3D Cursor
    view_3d_ki.from_id(1).shift = False
    view_3d_ki.from_id(1).alt = True
    # View Selected
    view_3d_ki.from_id(11).type = 'SPACE'
    # Snapping Panel
    view_3d_ki.from_id(111).properties.keep_open = True

    """ Image """
    image_ki = kc.keymaps['Image'].keymap_items

    # View Center
    image_ki.from_id(3).type = 'SPACE'

    """ Transform Modal Map """
    transform_modal_map_ki = kc.keymaps['Transform Modal Map'].keymap_items

    # Y Axis
    transform_modal_map_ki.from_id(7).type = 'C'
    # Y Plane
    transform_modal_map_ki.from_id(10).type = 'C'


def register():
    bpy.app.handlers.load_factory_startup_post.append(init_preferences)

But it seems when load_factory_startup_post triggers keymap still not initialized.
How to solve this?

I believe the only key configurations available at startup are ‘blender addon’, and I am not entirely sure as to why. The only potential solution I found could be this https://blender.stackexchange.com/a/131268, though I have not tried it myself. If you do try it, let us know if it works!

Thanx!

It is working tricky, but that’s what I ended up:

import threading
import time

import bpy
from bpy.app.handlers import load_factory_startup_post, persistent


@persistent
def startup(dummy):
    thread = threading.Thread(target=setup_keymap)
    thread.start()


def setup_keymap():
    kc = bpy.context.window_manager.keyconfigs['blender']
    
    # Here we must wait for all 205 keymaps to be loaded!
    while len(kc.keymaps) < 205:
        time.sleep(0.01)

    # Here you can modify keymap


def register():
    load_factory_startup_post.append(startup)
1 Like

If someone still reading, here is my current code for setup_keymap() part:

def setup_keymap():
    kc = bpy.context.window_manager.keyconfigs['blender']

    # Here we must wait for all 182 keymaps to be loaded!
    while len(kc.keymaps) < 182:
        print("Waiting for Keymaps...")
        time.sleep(0.01)

    # Now you can modify keymap

Im trying out your code and it’s not working. Even the “print(“Waiting for Keymaps…”)” is not showing in my console any idea? thx

Hi!
This code is supposed to run when blender starts, so script should be in “startup” folder. Also it is better to show off your code so people can say if anything is wrong.