1010import Settings
1111import Shared
1212from random import random
13+ from contextlib import contextmanager
1314from cadquery import cqgi
1415from Helpers import show
1516
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+
2142class 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