How to get keyconfig object with its path in Blender Python
This is a part of the project “Easy Keymap Generator”.
GOAL
To implement a function that get keyconfig name and return keyconfig object.
The list of keyconfig names can be seen in Preferences window.

Environment
Blender 2.83 (Python 3.7.4)
Windows 10
Method
This is my solution, but I don’t think it is the best way. Please let me know if you have any better ideas.
1 Access bpy.context.window_manager.keyconfigs
def get_keyconfig(keyconfig_name):
wm = bpy.context.window_manager
if keyconfig_name in wm.keyconfigs.keys():
return wm.keyconfigs[keyconfig_name]
else:
return None2 Activate specified keyconfig and return active keyconfig
If there is no keyconfig you’d like to get in current environment, you should activate the keyconfig by its path manually.
key_config_dict = get_keyconfig_dict()
configs = list(key_config_dict.keys())
print(configs)
# output => ['blender', 'blender_27x', 'industry_compatible', 'test1', 'test2']
kc = get_keyconfig(configs[1], key_config_dict)
print(kc)
# output => blender_27x <bpy_struct, KeyConfig("blender_27x")>2.1 Get keyconfigs and paths to the keyconfig file.
I created a function to get the dict with keys of keyconfig name and values of path to the keyconfig python file.
Reference: How to get key config list in Blender Python
def get_keyconfigs():
"""
:return: dict{kerconfig_name(str): path to config file(str)}
"""
config_pathes = bpy.utils.preset_paths("keyconfig")
config_dict = {}
for config_path in config_pathes:
for file in os.listdir(config_path):
name, ext = os.path.splitext(file)
if ext.lower() in [".py", ".xml"] and not name[0] == ".":
config_dict[name] = os.path.join(config_path, file)
return config_dict2.2 Activate specified keyconfig and return active keyconfig
Activate the specified keyconfig by its path and get active keyconfig with wm.keyconfigs.active then restore active keyconfig to original settings.
def get_keyconfig(keyconfig_name, keyconfig_dict):
wm = bpy.context.window_manager
if keyconfig_name in wm.keyconfigs.keys(): #if the keyconfig can be found, return it
return wm.keyconfigs[keyconfig_name]
else: # activate by config path and return it
keyconfig_path = keyconfig_dict[keyconfig_name]
current_path = keyconfig_dict[wm.keyconfigs.active.name]
bpy.ops.preferences.keyconfig_activate(filepath=keyconfig_path)
kc = wm.keyconfigs.active
bpy.ops.preferences.keyconfig_activate(filepath=current_path)
return kc