f = open('test.txt', 'r')
# getting class name
print(f.__class__.__name__)
#output => TextIOWrapper
# getting the module where the class is defined
print(f.__class__.__module__)
#output => _io
f.close()
def import_n_th_module(index):
"""
the function to get index number and import the module named mymodule+index such as mymodule1, mymodule2,...
"""
module_name = 'mymodule' + str(index)
# import module_name => the error occured
The purpose of the importlib package is two-fold. One is to provide the implementation of the import statement (and thus, by extension, the import() function) in Python source code. <omit>
I created 3 modules in modules package. And each module prints “[module_name] is imported” when being imported.
#test.py
import sys
import importlib
index = 3
importlib.import_module('modules.mymodule' + str(index))
# output => "mymodule3 is imported"
Postscript
Another purpose of the imporlib
Two, the components to implement import are exposed in this package, making it easier for users to create their own custom objects (known generically as an importer) to participate in the import process.
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_dict
2.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