PyAPI: add bpy.utils.execfile

Wraps `importlib.util`, avoids duplicate preset loading calls.
This commit is contained in:
2018-11-18 11:49:03 +11:00
parent f520f01b46
commit 0f1a63d34c
3 changed files with 17 additions and 17 deletions

View File

@@ -51,6 +51,7 @@ __all__ = (
"units",
"unregister_class",
"user_resource",
"execfile",
)
from _bpy import (
@@ -75,6 +76,18 @@ _script_module_dirs = "startup", "modules"
_is_factory_startup = _bpy.app.factory_startup
def execfile(filepath, mod=None):
# module name isn't used or added to 'sys.modules'.
# passing in 'mod' allows re-execution without having to reload.
import importlib.util
mod_spec = importlib.util.spec_from_file_location("__main__", filepath)
if mod is None:
mod = importlib.util.module_from_spec(mod_spec)
mod_spec.loader.exec_module(mod)
return mod
def _test_import(module_name, loaded_modules):
use_time = _bpy.app.debug_python
@@ -585,14 +598,7 @@ def keyconfig_set(filepath, report=None):
try:
error_msg = ""
with open(filepath, 'r', encoding='utf-8') as keyfile:
exec(
compile(keyfile.read(), filepath, "exec"),
{
"__file__": filepath,
"__name__": "__main__",
}
)
execfile(filepath)
except:
import traceback
error_msg = traceback.format_exc()

View File

@@ -511,7 +511,7 @@ def keyconfig_import_from_data(name, keyconfig_data):
def keyconfig_module_from_preset(name, preset_reference_filename=None):
import os
import importlib.util
import bpy
if preset_reference_filename is not None:
preset_path = os.path.join(os.path.dirname(preset_reference_filename), name + ".py")
else:
@@ -521,11 +521,7 @@ def keyconfig_module_from_preset(name, preset_reference_filename=None):
if not (preset_path and os.path.exists(preset_path)):
preset_path = bpy.utils.preset_find(name, "keyconfig")
# module name isn't used or added to 'sys.modules'.
mod_spec = importlib.util.spec_from_file_location("__main__", preset_path)
mod = importlib.util.module_from_spec(mod_spec)
mod_spec.loader.exec_module(mod)
return mod
return bpy.utils.execfile(preset_path)
# -----------------------------------------------------------------------------

View File

@@ -246,10 +246,8 @@ class ExecutePreset(Operator):
preset_class.reset_cb(context)
if ext == ".py":
import importlib.util
mod_spec = importlib.util.spec_from_file_location("__main__", filepath)
try:
mod_spec.loader.exec_module(importlib.util.module_from_spec(mod_spec))
bpy.utils.execfile(filepath)
except Exception as ex:
self.report({'ERROR'}, "Failed to execute the preset: " + repr(ex))