Skip to content

Commit 90668e3

Browse files
authored
Merge pull request #103 from fragmuffin/feature/import_module_reload
remove newly imported modules after script execution
2 parents 98da3e9 + 341aba2 commit 90668e3

File tree

1 file changed

+24
-2
lines changed

1 file changed

+24
-2
lines changed

Gui/Command.py

Lines changed: 24 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
import Settings
1111
import Shared
1212
from random import random
13+
from contextlib import contextmanager
1314
from cadquery import cqgi
1415
from Helpers import show
1516

@@ -18,6 +19,26 @@
1819
pythonopen = open
1920

2021

22+
@contextmanager
23+
def revert_sys_modules():
24+
"""
25+
Remove any new modules after context has exited
26+
>>> with revert_sys_modules():
27+
... import some_module
28+
... some_module.do_something()
29+
>>> some_module.do_something() # raises NameError: name 'some_module' is not defined
30+
"""
31+
modules_before = set(sys.modules.keys())
32+
try:
33+
yield
34+
finally:
35+
# irrespective of the succes of the context's execution, new modules
36+
# will be deleted upon exit
37+
for mod_name in sys.modules.keys():
38+
if mod_name not in modules_before:
39+
del sys.modules[mod_name]
40+
41+
2142
class CadQueryClearOutput:
2243
"""Allows the user to clear the reports view when it gets overwhelmed with output"""
2344

@@ -198,7 +219,8 @@ def Activated(self):
198219
os.environ["MYSCRIPT_DIR"] = os.path.dirname(os.path.abspath(cqCodePane.file.path))
199220

200221
# We import this way because using execfile() causes non-standard script execution in some situations
201-
imp.load_source('temp_module', tempFile.name)
222+
with revert_sys_modules():
223+
imp.load_source('temp_module', tempFile.name)
202224

203225
msg = QtGui.QApplication.translate(
204226
"cqCodeWidget",
@@ -429,4 +451,4 @@ def Activated(self):
429451
# Allows us to present parameters to users later that they can alter
430452
parameters = cqModel.metadata.parameters
431453

432-
Shared.populateParameterEditor(parameters)
454+
Shared.populateParameterEditor(parameters)

0 commit comments

Comments
 (0)