Merge pull request #103 from fragmuffin/feature/import_module_reload

remove newly imported modules after script execution
This commit is contained in:
Jeremy Wright 2017-10-09 07:35:28 -04:00 committed by GitHub
commit 90668e3af2

View File

@ -10,6 +10,7 @@ import module_locator
import Settings import Settings
import Shared import Shared
from random import random from random import random
from contextlib import contextmanager
from cadquery import cqgi from cadquery import cqgi
from Helpers import show from Helpers import show
@ -18,6 +19,26 @@ if open.__module__ == '__builtin__':
pythonopen = open pythonopen = open
@contextmanager
def revert_sys_modules():
"""
Remove any new modules after context has exited
>>> with revert_sys_modules():
... import some_module
... some_module.do_something()
>>> some_module.do_something() # raises NameError: name 'some_module' is not defined
"""
modules_before = set(sys.modules.keys())
try:
yield
finally:
# irrespective of the succes of the context's execution, new modules
# will be deleted upon exit
for mod_name in sys.modules.keys():
if mod_name not in modules_before:
del sys.modules[mod_name]
class CadQueryClearOutput: class CadQueryClearOutput:
"""Allows the user to clear the reports view when it gets overwhelmed with output""" """Allows the user to clear the reports view when it gets overwhelmed with output"""
@ -198,6 +219,7 @@ class CadQueryExecuteScript:
os.environ["MYSCRIPT_DIR"] = os.path.dirname(os.path.abspath(cqCodePane.file.path)) os.environ["MYSCRIPT_DIR"] = os.path.dirname(os.path.abspath(cqCodePane.file.path))
# We import this way because using execfile() causes non-standard script execution in some situations # We import this way because using execfile() causes non-standard script execution in some situations
with revert_sys_modules():
imp.load_source('temp_module', tempFile.name) imp.load_source('temp_module', tempFile.name)
msg = QtGui.QApplication.translate( msg = QtGui.QApplication.translate(