49 """ This method execute python code from an activeDocument (file) or direct
50 from editor (ui_scripter/editor/pythoneditor.py). When executing code
51 from a file, we use importlib to load this module/file and with
52 "users_script" name. That's implementation seeks for a "main()" function in the script.
53 When executing code from editor without creating a file, we compile
54 this script to bytecode and we execute this in an empty scope. That's
55 faster than use exec directly and cleaner, because we are using an empty scope. """
57 self.
scripter.uicontroller.setActiveWidget(i18n(
'Output'))
61 if (self.
editor._documentModified
is True):
62 output.write(
"==== Warning: Script not saved! ====\n")
64 output.write(
"======================================\n")
68 script = self.
editor.document().toPlainText()
69 document = self.
scripter.documentcontroller.activeDocument
72 if document
and self.
editor._documentModified
is False:
77 if hasattr(users_module,
"main")
and inspect.isfunction(users_module.main):
80 code = compile(script,
'<string>',
'exec')
81 globals_dict = {
"__name__": EXEC_NAMESPACE}
82 exec(code, globals_dict)
86 self.
scripter.uicontroller.closeScripter()
93 type_, value_, traceback_ = sys.exc_info()
94 if type_ == SyntaxError:
95 errorMessage =
"%s\n%s" % (value_.text.rstrip(),
" " * (value_.offset - 1) +
"^")
97 errorText =
"Syntax Error on line %s" % value_.lineno
98 elif type_ == IndentationError:
100 errorMessage = value_.text.rstrip()
101 errorText =
"Unexpected Indent on line %s" % value_.lineno
103 errorText = traceback.format_exception_only(type_, value_)[0]
104 format_string =
"In file: {0}\nIn function: {2} at line: {1}. Line with error:\n{3}"
105 tbList = traceback.extract_tb(traceback_)
107 errorMessage = format_string.format(*tb)
108 m =
"\n**********************\n%s\n%s\n**********************\n" % (errorText, errorMessage)
115 bottom = self.
output.verticalScrollBar().maximum()
116 self.
output.verticalScrollBar().setValue(bottom)
119 """ Loads and executes an external script using Python 3 specific operations
120 and returns the loaded module for further execution if needed.
122 spec = importlib.util.spec_from_file_location(EXEC_NAMESPACE, document.filePath)
124 users_module = importlib.util.module_from_spec(spec)
125 spec.loader.exec_module(users_module)
127 except AttributeError
as e:
128 if PYTHON34
or PYTHON33:
129 loader = SourceFileLoader(EXEC_NAMESPACE, document.filePath)
130 users_module = loader.load_module()