Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

remove newly imported modules after script execution #103

Merged
merged 1 commit into from
Oct 9, 2017
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
26 changes: 24 additions & 2 deletions Gui/Command.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
import Settings
import Shared
from random import random
from contextlib import contextmanager
from cadquery import cqgi
from Helpers import show

Expand All @@ -18,6 +19,26 @@
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:
"""Allows the user to clear the reports view when it gets overwhelmed with output"""

Expand Down Expand Up @@ -198,7 +219,8 @@ def Activated(self):
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
imp.load_source('temp_module', tempFile.name)
with revert_sys_modules():
imp.load_source('temp_module', tempFile.name)

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

Shared.populateParameterEditor(parameters)
Shared.populateParameterEditor(parameters)