def do_py(self, arg): ''' py <command>: Executes a Python command. py: Enters interactive Python mode. End with `Ctrl-D` (Unix) / `Ctrl-Z` (Windows), `quit()`, 'exit()`. Non-python commands can be issued with `cmd("your command")`. ''' arg = arg.parsed.raw[2:].strip() if arg.strip(): interp = InteractiveInterpreter(locals=self.pystate) interp.runcode(arg) else: interp = MyInteractiveConsole(locals=self.pystate) def quit(): raise EmbeddedConsoleExit def onecmd(arg): return self.onecmd(arg + '\n') self.pystate['quit'] = quit self.pystate['exit'] = quit self.pystate[self.nonpythoncommand] = onecmd try: cprt = 'Type "help", "copyright", "credits" or "license" for more information.' keepstate = Statekeeper(sys, ('stdin','stdout')) sys.stdout = self.stdout sys.stdin = self.stdin interp.interact(banner= "Python %s on %s\n%s\n(%s)\n%s" % (sys.version, sys.platform, cprt, self.__class__.__name__, self.do_py.__doc__)) except EmbeddedConsoleExit: pass keepstate.restore()
class Client(threading.Thread): def __init__(self, queue: list, id): super().__init__() self.id = id self.queue = queue self.result = [] variables = globals().copy() variables.update(locals()) self.interpreter = InteractiveInterpreter(variables) self.stop = False self.loading = False def run(self): self.interpreter.runcode("__name__ = '__main__'") while True: while len(self.queue) > 0: self.loading = True code = self.queue.pop(0) self.result.append(execute(self.interpreter, code)) self.loading = False time.sleep(1) if self.stop: break def push_code(self, code): self.queue.append(code) def get_result(self): while len(self.result) <= 0: pass result = self.result.pop(0) return result def close_client(self): self.stop = True
def execute(interpreter: InteractiveInterpreter, code): errors = "" old_stdout, old_stderr = sys.stdout, sys.stderr redirected_output = sys.stdout = StringIO() redirected_error = sys.stderr = StringIO() interpreter.runcode(code) sys.stdout, sys.stderr = old_stdout, old_stdout return {'output': redirected_output.getvalue(), 'error': redirected_error.getvalue()}
class ConsoleWindow(QtGui.QMainWindow, Ui_ConsoleWindow): def __init__(self, parent=None): super(ConsoleWindow, self).__init__(parent) self.setupUi(self) self.interp = InteractiveInterpreter({ '__name__': "__console__", '__doc__': None, 'retwin': parent, 'retapp': parent.application, 'conwin': self, 'sys': sys, }) outFormat = QtGui.QTextCharFormat() outFormat.setForeground(QtGui.QBrush(QtGui.QColor(0, 128, 0))) outFormat.setFontWeight(QtGui.QFont.Normal) errFormat = QtGui.QTextCharFormat() errFormat.setForeground(QtGui.QBrush(QtGui.QColor(255, 0, 0))) entryFormat = QtGui.QTextCharFormat() entryFormat.setFontWeight(QtGui.QFont.Bold) self.stdout = ConsoleOutputWriter( self.consoleOutput, "<stdout>", outFormat) self.stderr = ConsoleOutputWriter( self.consoleOutput, "<stderr>", errFormat) self.entry = ConsoleOutputWriter( self.consoleOutput, "<stdin>", entryFormat) self.consoleEntry.evaluate = self.evaluate return def evaluate(self, text): # Redirect stdout, stderr while executing the command try: saved_stdout, saved_stderr = sys.stdout, sys.stderr sys.stdout, sys.stderr = self.stdout, self.stderr try: compiled = compile_command(text, "<console>") if compiled is None: return False self.entry.write(">>> " + text.replace("\n", "\n... ") + "\n") self.interp.runcode(compiled) except Exception as e: print_exc() finally: sys.stdout, sys.stderr = saved_stdout, saved_stderr return True
def console_run(self, local_dict=None): self.run(backend=True) from code import InteractiveInterpreter i = InteractiveInterpreter(local_dict) while True: prompt = ">>>" try: line = raw_input(prompt) except EOFError: print("closing..") return i.runcode(line)
def console_run(self, local_dict=None): global BACKEND_UPDATE BACKEND_UPDATE = True self.run() from code import InteractiveInterpreter i = InteractiveInterpreter(local_dict) while True: prompt = ">>>" try: line = input(prompt) except EOFError: print("closing..") return i.runcode(line)
def runcodes(self): """Exécute les codes en attente.""" codes = list(self.codes) self.codes.clear() # Rétablit sus.stdout et sys.stderr stdout = sys.stdout stderr = sys.stderr sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ for code in codes: InteractiveInterpreter.runcode(self, code) sys.stdout = stdout sys.stderr = stderr
def runcodes(self): """Exécute les codes en attente.""" codes = list(self.codes) self.codes.clear() # Rétablit sus.stdout et sys.stderr stdout = sys.stdout stderr = sys.stderr sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ for code in codes: InteractiveInterpreter.runcode(self, code) sys.stdout = stdout sys.stderr = stderr
def execute_or_eval(self, mode, locals): """ Run the code """ basic_interpreter = InteractiveInterpreter(locals=locals) with tempfile.TemporaryFile( mode='w+', prefix='interpreter_error') as error_output: original_error = sys.stderr sys.stderr = error_output try: if mode == 'exec': code = compile(self.source, self.filename, 'exec') else: code = compile(self.expr, '<string>', 'eval') except: InteractiveInterpreter.showsyntaxerror(self.filename) sys.stderr.seek(0) result = sys.stderr.read() self.report.add_compilation_error('error', err_type='SyntaxError', details=result) return False else: # No compilation errors here if mode == 'exec': result = basic_interpreter.runcode(code) sys.stderr.seek(0) result = sys.stderr.read() if result: self.report.add_compilation_error( 'error', err_type='SyntaxError', details=result) return False else: sys.stdout.seek(0) result = sys.stdout.read() self.report.set_result(result) return True else: # mode eval try: result = eval(code, locals, locals) except Exception as err: a, b, tb = sys.exc_info() # Get the traceback object # Extract the information for the traceback corresponding to the error # inside the source code : [0] refers to the result = exec(code) # traceback, [1] refers to the last error inside code filename, lineno, file_type, line = traceback.extract_tb( tb)[1] print(traceback.format_exception(a, b, tb)) tb_str = "".join(traceback.format_exception_only(a, b)) self.report.add_execution_error('error', a.__name__, details=str(err)) return False self.report.set_result(result) return True finally: sys.stderr = original_error
def runcode(self, cmd): sys.stdout = self.stdout sys.stderr = self.stderr result = InteractiveInterpreter.runcode(self, cmd) sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ return result
def runcode(self, cmd): sys.stdout = self.stdout # sys.stdout.flush = flush sys.stderr = self.stderr # sys.stderr.flush = flush result = InteractiveInterpreter.runcode(self, cmd) sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ return result
def reverse(self, message): output = "00" compiledCode = None toCompile = self.sourceCodeReverse try: compiledCode = code.compile_command(toCompile, "string", "exec") except SyntaxError: errorMessage = traceback.format_exc().rstrip() if compiledCode is not None: try: # Initialize locals with the message locals = {'message': message} interpreter = InteractiveInterpreter(locals) # Run the compiled code interpreter.runcode(compiledCode) # Fetch the new value of message output = interpreter.locals['message'] except Exception, e: logging.warning("Error while appying function on a message : " + str(e))
def execute(event=None): save() code = text.get('1.0', END+'-1c') # stdin = sys.stdin stdout = sys.stdout stderr = sys.stderr output.delete('1.0', END) # def a(): # sys.stdin = StdinRedirector(output) # output.bind('<Return>', lambda: a) sys.stdout = StdoutRedirector(output) sys.stderr = StdoutRedirector(output) interp = InteractiveInterpreter() interp.runcode(code) sys.stdout = stdout sys.stderr = stderr
def execute_or_eval(self, mode, locals): """ Run the code """ basic_interpreter = InteractiveInterpreter(locals=locals) with tempfile.TemporaryFile(mode='w+', prefix='interpreter_error') as error_output: original_error = sys.stderr sys.stderr = error_output try: if mode == 'exec': code = compile(self.source, self.filename, 'exec') else: code = compile(self.expr, '<string>', 'eval') except: InteractiveInterpreter.showsyntaxerror(self.filename) sys.stderr.seek(0) result = sys.stderr.read() self.report.add_compilation_error('error', err_type='SyntaxError', details=result) return False else: # No compilation errors here if mode == 'exec': result = basic_interpreter.runcode(code) sys.stderr.seek(0) result = sys.stderr.read() if result: self.report.add_compilation_error('error', err_type='SyntaxError', details=result) return False else: sys.stdout.seek(0) result = sys.stdout.read() self.report.set_result(result) return True else: # mode eval try: result = eval(code, locals, locals) except Exception as err: a, b, tb = sys.exc_info() # Get the traceback object # Extract the information for the traceback corresponding to the error # inside the source code : [0] refers to the result = exec(code) # traceback, [1] refers to the last error inside code filename, lineno, file_type, line = traceback.extract_tb(tb)[1] print(traceback.format_exception(a, b, tb)) tb_str = "".join(traceback.format_exception_only(a, b)) self.report.add_execution_error('error', a.__name__, details=str(err)) return False self.report.set_result(result) return True finally: sys.stderr = original_error
def reverse(self, message): output = "00" compiledCode = None toCompile = self.sourceCodeReverse try: compiledCode = code.compile_command(toCompile, "string", "exec") except SyntaxError: errorMessage = traceback.format_exc().rstrip() if compiledCode is not None: try: # Initialize locals with the message locals = {'message': message} interpreter = InteractiveInterpreter(locals) # Run the compiled code interpreter.runcode(compiledCode) # Fetch the new value of message output = interpreter.locals['message'] except Exception, e: logging.warning( "Error while appying function on a message : " + str(e))
def handle(self, *args, **options): self._initialize_paths() self._check_settings() self._check_configs() settings = open(self.settings_path, 'r') db_braces = 0 db_lines = [] other_lines = [] debug_line, template_debug_line = None, None for line in settings: if line.startswith('DEBUG'): debug_line = line elif line.startswith('TEMPLATE_DEBUG'): template_debug_line = line elif line.startswith('DATABASES') and '{' in line: db_braces = 1 db_lines.append(line) elif db_braces: db_lines.append(line) if '{' in line: db_braces += 1 elif '}' in line: db_braces -= 1 else: other_lines.append(line) new_settings_path = os.path.join(self.base, 'new_settings.py') with open(new_settings_path, 'w') as new_settings: new_settings.write(CODE) new_settings.write(''.join(other_lines)) context = InteractiveInterpreter() context.runcode(''.join(db_lines)) if debug_line: context.runcode(debug_line) if template_debug_line: context.runcode(template_debug_line) if not os.path.exists(self.configs_path): os.mkdir(self.configs_path) config = RawConfigParser() config.add_section('debug') config.set('debug', 'DEBUG', context.locals['DEBUG']) config.set('debug', 'TEMPLATE_DEBUG', context.locals['TEMPLATE_DEBUG']) db_attrs = ['ENGINE', 'NAME', 'USER', 'PASSWORD', 'HOST', 'PORT'] config.add_section('database') for x in db_attrs: config.set('database', x, context.locals['DATABASES']['default'][x]) with open(self.default_config_path, 'w') as config_file: config.write(config_file) #and now switch the configs shutil.move(self.settings_path, os.path.join(self.base, 'old_settings.py')) shutil.move(new_settings_path, self.settings_path)
def runcode(self, cmd): InteractiveInterpreter.runcode(self, cmd)
class QShell(QtGui.QTextEdit): """This class embeds a python interperter in a QTextEdit Widget It is based on PyCute developed by Gerard Vermeulen. """ def __init__(self, locals=None, parent=None): """Constructor. The optional 'locals' argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key "__name__" set to "__console__" and key "__doc__" set to None. The optional 'log' argument specifies the file in which the interpreter session is to be logged. The optional 'parent' argument specifies the parent widget. If no parent widget has been specified, it is possible to exit the interpreter by Ctrl-D. """ QtGui.QTextEdit.__init__(self, parent) self.setReadOnly(False) self.setWindowTitle("Console") # to exit the main interpreter by a Ctrl-D if QShell has no parent if parent is None: self.eofKey = QtCore.Qt.Key_D else: self.eofKey = None # flag for knowing when selecting text self.selectMode = False self.interpreter = None self.controller = None # storing current state #this is not working on mac #self.prev_stdout = sys.stdout #self.prev_stdin = sys.stdin #self.prev_stderr = sys.stderr # capture all interactive input/output #sys.stdout = self #sys.stderr = self #sys.stdin = self # user interface setup self.setAcceptRichText(False) self.setWordWrapMode(QtGui.QTextOption.WrapAnywhere) conf = get_vistrails_configuration() shell_conf = conf.shell # font font = QtGui.QFont(shell_conf.font_face, shell_conf.font_size) font.setFixedPitch(1) self.setFont(font) self.reset(locals) def load_package(self, pkg_name): reg = core.modules.module_registry.get_module_registry() package = reg.get_package_by_name(pkg_name) def create_dict(modules, ns, m, mdesc): md = {} if len(ns) == 0: d = { '_module_desc': mdesc, '_package': pkg, } modules[m] = type('module', (vistrails_module, ), d) else: if ns[0] in modules: md = create_dict(modules[ns[0]], ns[1:], m, mdesc) else: md = create_dict(md, ns[1:], m, mdesc) modules[ns[0]] = md return modules def create_namespace_path(root, modules): for k, v in modules.iteritems(): if type(v) == type({}): d = create_namespace_path(k, v) modules[k] = d if root is not None: modules['_package'] = pkg return type(root, (object, ), modules)() else: return modules def get_module_init(module_desc): def init(self, *args, **kwargs): self.__dict__['module'] = \ api.add_module_from_descriptor(module_desc) return init def get_module(package): def getter(self, attr_name): desc_tuple = (attr_name, '') if desc_tuple in package.descriptors: module_desc = package.descriptors[desc_tuple] d = { '_module_desc': module_desc, '_package': self, } return type('module', (vistrails_module, ), d) else: raise AttributeError("type object '%s' has no attribute " "'%s'" % (self.__class__.__name__, attr_name)) return getter d = { '__getattr__': get_module(package), } pkg = type(package.name, (object, ), d)() modules = {} for (m, ns) in package.descriptors: module_desc = package.descriptors[(m, ns)] modules = create_dict(modules, ns.split('|'), m, module_desc) modules = create_namespace_path(None, modules) for (k, v) in modules.iteritems(): setattr(pkg, k, v) return pkg def selected_modules(self): shell_modules = [] modules = api.get_selected_modules() for module in modules: d = {'_module': module} shell_modules.append(type('module', (vistrails_module, ), d)()) return shell_modules def reset(self, locals): """reset(locals) -> None Reset shell preparing it for a new session. """ locals['load_package'] = self.load_package locals['selected_modules'] = self.selected_modules if self.interpreter: del self.interpreter self.interpreter = InteractiveInterpreter(locals) # last line + last incomplete lines self.line = QtCore.QString() self.lines = [] # the cursor position in the last line self.point = 0 # flag: the interpreter needs more input to run the last lines. self.more = 0 # flag: readline() is being used for e.g. raw_input() and input() self.reading = 0 # history self.history = [] self.pointer = 0 self.last = 0 # interpreter prompt. if hasattr(sys, "ps1"): sys.ps1 else: sys.ps1 = ">>> " if hasattr(sys, "ps2"): sys.ps2 else: sys.ps2 = "... " # interpreter banner self.write('VisTrails shell running Python %s on %s.\n' % (sys.version, sys.platform)) self.write('Type "copyright", "credits" or "license"' ' for more information on Python.\n') self.write(sys.ps1) def flush(self): """flush() -> None. Simulate stdin, stdout, and stderr. """ pass def isatty(self): """isatty() -> int Simulate stdin, stdout, and stderr. """ return 1 def readline(self): """readline() -> str Simulate stdin, stdout, and stderr. """ self.reading = 1 self.__clearLine() cursor = self.textCursor() cursor.movePosition(QtGui.QTextCursor.End) self.setTextCursor(cursor) app = QtGui.QApplication.instance() while self.reading: app.processOneEvent() if self.line.length() == 0: return '\n' else: return str(self.line) def write(self, text): """write(text: str) -> None Simulate stdin, stdout, and stderr. """ cursor = self.textCursor() cursor.movePosition(QtGui.QTextCursor.End) cursor.clearSelection() self.setTextCursor(cursor) self.insertPlainText(text) cursor = self.textCursor() self.last = cursor.position() def write_input(self, text): cursor = self.textCursor() cursor.movePosition(QtGui.QTextCursor.End) cursor.clearSelection() self.setTextCursor(cursor) self.__insertText(text) def write_and_exec(self, commandlist): for command in commandlist: self.write_input(command) self.__run() def insertFromMimeData(self, source): if source.hasText(): cmds = source.text().split(QtCore.QString('\n')) self.write_and_exec(cmds) def scroll_bar_at_bottom(self): """Returns true if vertical bar exists and is at bottom, or if vertical bar does not exist.""" bar = self.verticalScrollBar() if not bar: return True return bar.value() == bar.maximum() def __run(self): """__run() -> None Append the last line to the history list, let the interpreter execute the last line(s), and clean up accounting for the interpreter results: (1) the interpreter succeeds (2) the interpreter fails, finds no errors and wants more line(s) (3) the interpreter fails, finds errors and writes them to sys.stderr """ cursor = self.textCursor() cursor.movePosition(QtGui.QTextCursor.End) self.setTextCursor(cursor) # self.set_controller() should_scroll = self.scroll_bar_at_bottom() self.pointer = 0 self.history.append(QtCore.QString(self.line)) self.lines.append(str(self.line)) source = '\n'.join(self.lines) self.write('\n') self.more = self.interpreter.runsource(source) if self.more: self.write(sys.ps2) else: self.write(sys.ps1) self.lines = [] self.__clearLine() if should_scroll: bar = self.verticalScrollBar() if bar: bar.setValue(bar.maximum()) def __clearLine(self): """__clearLine() -> None Clear input line buffer. """ self.line.truncate(0) self.point = 0 def __insertText(self, text): """__insertText(text) -> None Insert text at the current cursor position. """ self.insertPlainText(text) self.line.insert(self.point, text) self.point += text.length() # def add_pipeline(self, p): # """ # add_pipeline(p) -> None # Set the active pipeline in the command shell. This replaces the modules # variable with the list of current active modules of the selected pipeline. # """ # if self.controller: # self.interpreter.active_pipeline = self.controller.current_pipeline # else: # self.interpreter.active_pipeline = p # cmd = 'active_pipeline = self.shell.interpreter.active_pipeline' # self.interpreter.runcode(cmd) # cmd = 'modules = self.vistrails_interpreter.find_persistent_entities(active_pipeline)[0]' # self.interpreter.runcode(cmd) def set_controller(self, controller=None): """set_controller(controller: VistrailController) -> None Set the current VistrailController on the shell. """ self.controller = controller if controller and self.controller.current_pipeline: self.interpreter.active_pipeline = self.controller.current_pipeline cmd = 'run_pipeline = self.shell.run_pipeline' self.interpreter.runcode(cmd) cmd = 'active_pipeline = self.shell.interpreter.active_pipeline' self.interpreter.runcode(cmd) cmd = 'modules = self.vistrails_interpreter.' \ 'find_persistent_entities(active_pipeline)[0]' self.interpreter.runcode(cmd) # def set_pipeline(self): # """set_active_pipeline() -> None # Makes sure that the pipeline being displayed is present in the shell for # direct inspection and manipulation # """ # self.add_pipeline(None) def run_pipeline(self): if self.controller: if self.interpreter.active_pipeline: self.controller.execute_current_workflow() def keyPressEvent(self, e): """keyPressEvent(e) -> None Handle user input a key at a time. Notice that text might come more than one keypress at a time if user is a fast enough typist! """ text = e.text() key = e.key() # NB: Sometimes len(str(text)) > 1! if text.length() and all( ord(x) >= 32 and ord(x) < 127 for x in str(text)): # exit select mode and jump to end of text cursor = self.textCursor() if self.selectMode or cursor.hasSelection(): self.selectMode = False cursor.movePosition(QtGui.QTextCursor.End) cursor.clearSelection() self.setTextCursor(cursor) self.__insertText(text) return if e.modifiers() & QtCore.Qt.MetaModifier and key == self.eofKey: self.parent().closeSession() if e.modifiers() & QtCore.Qt.ControlModifier: if key == QtCore.Qt.Key_C or key == QtCore.Qt.Key_Insert: self.copy() elif key == QtCore.Qt.Key_V: cursor = self.textCursor() cursor.movePosition(QtGui.QTextCursor.End) cursor.clearSelection() self.setTextCursor(cursor) self.paste() elif key == QtCore.Qt.Key_A: self.selectAll() self.selectMode = True else: e.ignore() return if e.modifiers() & QtCore.Qt.ShiftModifier: if key == QtCore.Qt.Key_Insert: cursor = self.textCursor() cursor.movePosition(QtGui.QTextCursor.End) cursor.clearSelection() self.setTextCursor(cursor) self.paste() else: e.ignore() return # exit select mode and jump to end of text cursor = self.textCursor() if self.selectMode or cursor.hasSelection(): self.selectMode = False cursor.movePosition(QtGui.QTextCursor.End) cursor.clearSelection() self.setTextCursor(cursor) if key == QtCore.Qt.Key_Backspace: if self.point: QtGui.QTextEdit.keyPressEvent(self, e) self.point -= 1 self.line.remove(self.point, 1) elif key == QtCore.Qt.Key_Delete: QtGui.QTextEdit.keyPressEvent(self, e) self.line.remove(self.point, 1) elif key == QtCore.Qt.Key_Return or key == QtCore.Qt.Key_Enter: if self.reading: self.reading = 0 else: self.__run() elif key == QtCore.Qt.Key_Tab: self.__insertText(text) elif key == QtCore.Qt.Key_Left: if self.point: QtGui.QTextEdit.keyPressEvent(self, e) self.point -= 1 elif key == QtCore.Qt.Key_Right: if self.point < self.line.length(): QtGui.QTextEdit.keyPressEvent(self, e) self.point += 1 elif key == QtCore.Qt.Key_Home: cursor = self.textCursor() cursor.movePosition(QtGui.QTextCursor.StartOfLine) cursor.setPosition(cursor.position() + 4) self.setTextCursor(cursor) self.point = 0 elif key == QtCore.Qt.Key_End: QtGui.QTextEdit.keyPressEvent(self, e) self.point = self.line.length() elif key == QtCore.Qt.Key_Up: if len(self.history): if self.pointer == 0: self.pointer = len(self.history) self.pointer -= 1 self.__recall() elif key == QtCore.Qt.Key_Down: if len(self.history): self.pointer += 1 if self.pointer == len(self.history): self.pointer = 0 self.__recall() else: e.ignore() def __recall(self): """__recall() -> None Display the current item from the command history. """ cursor = self.textCursor() cursor.setPosition(self.last) cursor.select(QtGui.QTextCursor.LineUnderCursor) cursor.removeSelectedText() self.setTextCursor(cursor) self.insertPlainText(sys.ps1) self.__clearLine() self.__insertText(self.history[self.pointer]) def focusNextPrevChild(self, next): """focusNextPrevChild(next) -> None Suppress tabbing to the next window in multi-line commands. """ if next and self.more: return 0 return QtGui.QTextEdit.focusNextPrevChild(self, next) def mousePressEvent(self, e): """mousePressEvent(e) -> None Keep the cursor after the last prompt. """ if e.button() == QtCore.Qt.LeftButton: self.selectMode = True QtGui.QTextEdit.mousePressEvent(self, e) # cursor = self.textCursor() # cursor.movePosition(QtGui.QTextCursor.End) # self.setTextCursor(cursor) return def hide(self): """suspend() -> None Called when hiding the parent window in order to recover the previous state. """ #recovering the state sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ sys.stdin = sys.__stdin__ def show(self): """show() -> None Store previous state and starts capturing all interactive input and output. """ # capture all interactive input/output sys.stdout = self sys.stderr = self sys.stdin = self self.setFocus() def saveSession(self, fileName): """saveSession(fileName: str) -> None Write its contents to a file """ output = open(str(fileName), 'w') output.write(self.toPlainText()) output.close() def restart(self, locals=None): """restart(locals=None) -> None Restart a new session """ self.clear() self.reset(locals) def contentsContextMenuEvent(self, ev): """ contentsContextMenuEvent(ev) -> None Suppress the right button context menu. """ return
class QShell(QtGui.QTextEdit): """This class embeds a python interperter in a QTextEdit Widget It is based on PyCute developed by Gerard Vermeulen. """ def __init__(self, locals=None, parent=None): """Constructor. The optional 'locals' argument specifies the dictionary in which code will be executed; it defaults to a newly created dictionary with key "__name__" set to "__console__" and key "__doc__" set to None. The optional 'log' argument specifies the file in which the interpreter session is to be logged. The optional 'parent' argument specifies the parent widget. If no parent widget has been specified, it is possible to exit the interpreter by Ctrl-D. """ QtGui.QTextEdit.__init__(self, parent) self.setReadOnly(False) self.setWindowTitle("Console") # to exit the main interpreter by a Ctrl-D if QShell has no parent if parent is None: self.eofKey = QtCore.Qt.Key_D else: self.eofKey = None # flag for knowing when selecting text self.selectMode = False self.interpreter = None self.controller = None # storing current state #this is not working on mac #self.prev_stdout = sys.stdout #self.prev_stdin = sys.stdin #self.prev_stderr = sys.stderr # capture all interactive input/output #sys.stdout = self #sys.stderr = self #sys.stdin = self # user interface setup self.setAcceptRichText(False) self.setWordWrapMode(QtGui.QTextOption.WrapAnywhere) conf = get_vistrails_configuration() shell_conf = conf.shell # font font = QtGui.QFont(shell_conf.font_face, shell_conf.font_size) font.setFixedPitch(1) self.setFont(font) self.reset(locals) def load_package(self, pkg_name): reg = vistrails.core.modules.module_registry.get_module_registry() package = reg.get_package_by_name(pkg_name) def create_dict(modules, ns, m, mdesc): md = {} if len(ns) == 0: d = {'_module_desc': mdesc, '_package': pkg,} modules[m] = type('module', (vistrails_module,), d) else: if ns[0] in modules: md = create_dict(modules[ns[0]], ns[1:], m, mdesc) else: md = create_dict(md, ns[1:], m, mdesc) modules[ns[0]] = md return modules def create_namespace_path(root, modules): for k,v in modules.iteritems(): if isinstance(v, dict): d = create_namespace_path(k,v) modules[k] = d if root is not None: modules['_package'] = pkg return type(root, (object,), modules)() else: return modules def get_module_init(module_desc): def init(self, *args, **kwargs): self.__dict__['module'] = \ vistrails.api.add_module_from_descriptor(module_desc) return init def get_module(package): def getter(self, attr_name): desc_tuple = (attr_name, '') if desc_tuple in package.descriptors: module_desc = package.descriptors[desc_tuple] d = {'_module_desc': module_desc, '_package': self,} return type('module', (vistrails_module,), d) else: raise AttributeError("type object '%s' has no attribute " "'%s'" % (self.__class__.__name__, attr_name)) return getter d = {'__getattr__': get_module(package),} pkg = type(package.name, (object,), d)() modules = {} for (m,ns) in package.descriptors: module_desc = package.descriptors[(m,ns)] modules = create_dict(modules, ns.split('|'), m, module_desc) modules = create_namespace_path(None, modules) for (k,v) in modules.iteritems(): setattr(pkg, k, v) return pkg def selected_modules(self): shell_modules = [] modules = vistrails.api.get_selected_modules() for module in modules: d = {'_module': module} shell_modules.append(type('module', (vistrails_module,), d)()) return shell_modules def reset(self, locals): """reset(locals) -> None Reset shell preparing it for a new session. """ locals['load_package'] = self.load_package locals['selected_modules'] = self.selected_modules if self.interpreter: del self.interpreter self.interpreter = InteractiveInterpreter(locals) # last line + last incomplete lines self.line = '' self.lines = [] # the cursor position in the last line self.point = 0 # flag: the interpreter needs more input to run the last lines. self.more = 0 # flag: readline() is being used for e.g. raw_input() and input() self.reading = 0 # history self.history = [] self.pointer = 0 self.last = 0 # interpreter prompt. if hasattr(sys, "ps1"): sys.ps1 else: sys.ps1 = ">>> " if hasattr(sys, "ps2"): sys.ps2 else: sys.ps2 = "... " # interpreter banner self.write('VisTrails shell running Python %s on %s.\n' % (sys.version, sys.platform)) self.write('Type "copyright", "credits" or "license"' ' for more information on Python.\n') self.write(sys.ps1) def flush(self): """flush() -> None. Simulate stdin, stdout, and stderr. """ pass def isatty(self): """isatty() -> int Simulate stdin, stdout, and stderr. """ return 1 def readline(self): """readline() -> str Simulate stdin, stdout, and stderr. """ self.reading = 1 self.__clearLine() cursor = self.textCursor() cursor.movePosition(QtGui.QTextCursor.End) self.setTextCursor(cursor) while self.reading: qApp.processOneEvent() if len(self.line) == 0: return '\n' else: return self.line def write(self, text): """write(text: str) -> None Simulate stdin, stdout, and stderr. """ cursor = self.textCursor() cursor.movePosition(QtGui.QTextCursor.End) cursor.clearSelection() self.setTextCursor(cursor) self.insertPlainText(text) cursor = self.textCursor() self.last = cursor.position() def insertFromMimeData(self, source): if source.hasText(): cursor = self.textCursor() cursor.movePosition(QtGui.QTextCursor.End) cursor.clearSelection() self.setTextCursor(cursor) self.__insertText(source.text()) def scroll_bar_at_bottom(self): """Returns true if vertical bar exists and is at bottom, or if vertical bar does not exist.""" bar = self.verticalScrollBar() if not bar: return True return bar.value() == bar.maximum() def __run(self): """__run() -> None Append the last line to the history list, let the interpreter execute the last line(s), and clean up accounting for the interpreter results: (1) the interpreter succeeds (2) the interpreter fails, finds no errors and wants more line(s) (3) the interpreter fails, finds errors and writes them to sys.stderr """ cursor = self.textCursor() cursor.movePosition(QtGui.QTextCursor.End) self.setTextCursor(cursor) # self.set_controller() should_scroll = self.scroll_bar_at_bottom() self.pointer = 0 self.history.append(self.line) self.lines.append(self.line) source = '\n'.join(self.lines) self.write('\n') self.more = self.interpreter.runsource(source) if self.more: self.write(sys.ps2) else: self.write(sys.ps1) self.lines = [] self.__clearLine() if should_scroll: bar = self.verticalScrollBar() if bar: bar.setValue(bar.maximum()) def __clearLine(self): """__clearLine() -> None Clear input line buffer. """ self.line = "" self.point = 0 def __insertText(self, text): """__insertText(text) -> None Insert text at the current cursor position. """ self.insertPlainText(text) self.line = self.line[:self.point] + text + self.line[self.point:] self.point += len(text) # def add_pipeline(self, p): # """ # add_pipeline(p) -> None # Set the active pipeline in the command shell. This replaces the modules # variable with the list of current active modules of the selected pipeline. # """ # if self.controller: # self.interpreter.active_pipeline = self.controller.current_pipeline # else: # self.interpreter.active_pipeline = p # cmd = 'active_pipeline = self.shell.interpreter.active_pipeline' # self.interpreter.runcode(cmd) # cmd = 'modules = self.vistrails_interpreter.find_persistent_entities(active_pipeline)[0]' # self.interpreter.runcode(cmd) def set_controller(self, controller=None): """set_controller(controller: VistrailController) -> None Set the current VistrailController on the shell. """ self.controller = controller if controller: self.interpreter.active_pipeline = self.controller.current_pipeline cmd = 'active_pipeline = self.shell.interpreter.active_pipeline' self.interpreter.runcode(cmd) cmd = 'modules = self.vistrails_interpreter.' \ 'find_persistent_entities(active_pipeline)[0]' self.interpreter.runcode(cmd) # def set_pipeline(self): # """set_active_pipeline() -> None # Makes sure that the pipeline being displayed is present in the shell for # direct inspection and manipulation # """ # self.add_pipeline(None) def keyPressEvent(self, e): """keyPressEvent(e) -> None Handle user input a key at a time. Notice that text might come more than one keypress at a time if user is a fast enough typist! """ text = e.text() key = e.key() # NB: Sometimes len(str(text)) > 1! if len(text) and all(ord(x) >= 32 and ord(x) < 127 for x in str(text)): # exit select mode and jump to end of text cursor = self.textCursor() if self.selectMode or cursor.hasSelection(): self.selectMode = False cursor.movePosition(QtGui.QTextCursor.End) cursor.clearSelection() self.setTextCursor(cursor) self.__insertText(text) return if e.modifiers() & QtCore.Qt.MetaModifier and key == self.eofKey: self.parent().closeSession() if e.modifiers() & QtCore.Qt.ControlModifier: if key == QtCore.Qt.Key_C or key == QtCore.Qt.Key_Insert: self.copy() elif key == QtCore.Qt.Key_V: cursor = self.textCursor() cursor.movePosition(QtGui.QTextCursor.End) cursor.clearSelection() self.setTextCursor(cursor) self.paste() elif key == QtCore.Qt.Key_A: self.selectAll() self.selectMode = True else: e.ignore() return if e.modifiers() & QtCore.Qt.ShiftModifier: if key == QtCore.Qt.Key_Insert: cursor = self.textCursor() cursor.movePosition(QtGui.QTextCursor.End) cursor.clearSelection() self.setTextCursor(cursor) self.paste() else: e.ignore() return # exit select mode and jump to end of text cursor = self.textCursor() if self.selectMode or cursor.hasSelection(): self.selectMode = False cursor.movePosition(QtGui.QTextCursor.End) cursor.clearSelection() self.setTextCursor(cursor) if key == QtCore.Qt.Key_Backspace: if self.point: QtGui.QTextEdit.keyPressEvent(self, e) self.point -= 1 self.line = self.line[:self.point] + self.line[self.point+1:] elif key == QtCore.Qt.Key_Delete: QtGui.QTextEdit.keyPressEvent(self, e) self.line = self.line[:self.point] + self.line[self.point+1:] elif key == QtCore.Qt.Key_Return or key == QtCore.Qt.Key_Enter: if self.reading: self.reading = 0 else: self.__run() elif key == QtCore.Qt.Key_Tab: self.__insertText(text) elif key == QtCore.Qt.Key_Left: if self.point: QtGui.QTextEdit.keyPressEvent(self, e) self.point -= 1 elif key == QtCore.Qt.Key_Right: if self.point < len(self.line): QtGui.QTextEdit.keyPressEvent(self, e) self.point += 1 elif key == QtCore.Qt.Key_Home: cursor = self.textCursor() cursor.movePosition(QtGui.QTextCursor.StartOfLine) cursor.setPosition(cursor.position() + 4) self.setTextCursor(cursor) self.point = 0 elif key == QtCore.Qt.Key_End: QtGui.QTextEdit.keyPressEvent(self, e) self.point = len(self.line) elif key == QtCore.Qt.Key_Up: if len(self.history): if self.pointer == 0: self.pointer = len(self.history) self.pointer -= 1 self.__recall() elif key == QtCore.Qt.Key_Down: if len(self.history): self.pointer += 1 if self.pointer == len(self.history): self.pointer = 0 self.__recall() else: e.ignore() def __recall(self): """__recall() -> None Display the current item from the command history. """ cursor = self.textCursor() cursor.setPosition(self.last) cursor.select(QtGui.QTextCursor.LineUnderCursor) cursor.removeSelectedText() self.setTextCursor(cursor) self.insertPlainText(sys.ps1) self.__clearLine() self.__insertText(self.history[self.pointer]) def focusNextPrevChild(self, next): """focusNextPrevChild(next) -> None Suppress tabbing to the next window in multi-line commands. """ if next and self.more: return 0 return QtGui.QTextEdit.focusNextPrevChild(self, next) def mousePressEvent(self, e): """mousePressEvent(e) -> None Keep the cursor after the last prompt. """ if e.button() == QtCore.Qt.LeftButton: self.selectMode = True QtGui.QTextEdit.mousePressEvent(self, e) # cursor = self.textCursor() # cursor.movePosition(QtGui.QTextCursor.End) # self.setTextCursor(cursor) return def hide(self): """suspend() -> None Called when hiding the parent window in order to recover the previous state. """ #recovering the state sys.stdout = sys.__stdout__ sys.stderr = sys.__stderr__ sys.stdin = sys.__stdin__ def show(self): """show() -> None Store previous state and starts capturing all interactive input and output. """ # capture all interactive input/output sys.stdout = self sys.stderr = self sys.stdin = self self.setFocus() def saveSession(self, fileName): """saveSession(fileName: str) -> None Write its contents to a file """ output = open(str(fileName), 'w') output.write(self.toPlainText()) output.close() def restart(self, locals=None): """restart(locals=None) -> None Restart a new session """ self.clear() self.reset(locals) def contentsContextMenuEvent(self,ev): """ contentsContextMenuEvent(ev) -> None Suppress the right button context menu. """ return
class DevConsole(QtWidgets.QMainWindow, QtWidgets.QDialog, Ui_devConsole): ''' DevConsole self.qtTools = kmxQtCommonTools.CommonTools(self.win, self.iconPath) self.qtTools.applyStyle() dv = self.qtTools.getIconString('/04/16/39.png') self.qtConsole = DevConsolePlug.DevConsole(self.win, ShowPrint=True, ShowError=True, StatusBar=self.win.statusBar, AsDock=True, InitalizeScripts=True, logCount=30, btnIcon=dv, addObj=self) Arguments: ShowPrint... Captures all print outputs to DevConsole o/p ShowError... Captures all error info outputs to DevConsole o/p Methods: appendPlainOutput(txt) ... Append plain text into DevConsole o/p appendSplOutput(txt) ... Append TimeStamped text into DevConsole o/p ''' def __init__(self, parent=None, ShowPrint=True, ShowError=True, StatusBar=None, AsDock=False, logCount=30, ScriptsPath='Scripts/', InitalizeScripts=True, btnText="Console", btnIcon="F:/04/06/29.PNG", addObj=None): ''' Parent - Pass QWIDGET based objects. Else I will create my own. ShowPrint - Redirect standard prints ShowError - Redirect standard errors StatusBar - Attach DevC Invoke button to this status bar else You should invoke DevC explicitly AsDock - If True creates DevC as a dock else as a dialog window ''' last_update_date = 'July 02 2015' # July 02 2015 , Jan 12 2013 self.addObj = addObj self.parent = parent self.asDock = AsDock self.logCount = logCount super(DevConsole, self).__init__(self.parent) atexit.register(self.writeToLog) # Load File self.loadedFile = False self.loadedFileName = '' self.pyDesigner = 'C:\Python34\Lib\site-packages\PyQt5\designer.exe' #Flags self.qtTools = kmxQtCommonTools.CommonTools(self) self.ttls = kmxTools.Tools() self.qtTree = kmxQtTreeWidget.TreeWidget() self.qtMenu = kmxQtMenuBuilder.MenuBuilder() self.qtConn = kmxQtConnections.QtConnections(self) self.qtIcon = kmxQtCommonTools.iconSetup(self) self.standalone = 0 if self.parent else 1 if self.standalone: print('No parent specified! Creating standalone console!') self.parent = self.win = QtWidgets.QMainWindow() self.win.resize(689, 504) self.mainWidget = QtWidgets.QWidget(self.win) self.setupUi(self.mainWidget) self.win.setCentralWidget(self.mainWidget) self.toolbar = QtWidgets.QToolBar('Main Tools', self) self.toolbar2 = QtWidgets.QToolBar('Additional Tools', self) self.toolbar.setFloatable(True) self.toolbar2.setFloatable(True) self.win.addToolBar(self.toolbar) self.win.addToolBar(self.toolbar2) self.setStandAloneModeFeatures() self.btnExecute.setVisible(0) self.btnLoadScript.setVisible(0) self.btnSaveScript.setVisible(0) self.btnNewScript.setVisible(0) self.btnQuickSaveScript.setVisible(0) self.label.setVisible(1) self.label.setText('Output:') self.line.setVisible(0) #self.sciOutput.resize(self.sciOutput.width(), self.sciOutput.height() + 90) elif self.asDock: if hasattr(self.parent, 'addDockWidget'): print('Creating dock based console!') self.win = QtWidgets.QDockWidget(self.parent) base = QtWidgets.QWidget() self.setupUi(base) self.win.setWidget(base) self.parent.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.win) # print ('Creating dock based console!') # self.dck = QtWidgets.QDockWidget(self.parent) # # dlg = QtWidgets.QWidget() # # self.win = QtWidgets.QMainWindow() # lyt = QtWidgets.QVBoxLayout() # lyt.addWidget(self.win) # wdgt = QtWidgets.QWidget(self.dck) # self.setupUi(wdgt) # self.win.setCentralWidget(wdgt) # # dlg.setLayout(lyt) # # self.dck.setWidget(dlg) # self.parent.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.dck) else: print('Unsupported Parent for creating dock based console! ' + str(self.parent)) print('Connecting console to given parent as a dialog...' + str(self.parent)) self.win = QtWidgets.QDialog(self.parent) self.setupUi(self.win) else: print('Connecting console to given parent as a dialog...' + str(self.parent)) self.win = QtWidgets.QDialog(self.parent) self.setupUi(self.win) self.outputFont = self.sciOutput.font() self.outputFont.setFamily("Courier") self.outputFont.setPointSize(10) self.outputFont.setFixedPitch(True) self.sciOutput.setFont(self.outputFont) self.sciOutput.setMarginsFont(self.outputFont) print( "Outputs Redirected to HaPy. Check HaPy console log for furthur system messages." ) if ShowPrint: sys.stdout = self if ShowError: sys.stderr = self self.inter = InteractiveInterpreter() self.inter.locals['dev'] = self globals()['dev'] = self self.win.setWindowIcon(self.parent.windowIcon()) self.win.setWindowTitle('HaPy') self.PLX = Qsci.QsciLexerPython(self) self.ABS = Qsci.QsciAPIs(self.PLX) # self.PLX.setAPIs(self.ABS) self.ABS.prepare() self.sciOutput.setReadOnly(1) self._setQSci(self.sciOutput) # Connections self.tabWidget.tabCloseRequested.connect(self.tabClose) if not self.standalone: self.btnExecute.clicked.connect(self.btnRedirector) #self.btnExecute_2.clicked.connect(self.btnRedirector) self.btnLoadScript.clicked.connect(self.btnRedirector) self.btnSaveScript.clicked.connect(self.btnRedirector) self.btnNewScript.clicked.connect(self.btnRedirector) self.btnQuickSaveScript.clicked.connect(self.btnRedirector) self.qtTools.connectToRightClick(self.treeWidget, self.pluginRightClick) self.tabWidget.__class__.keyReleaseEvent = self.tabKeyPress if StatusBar: self.stsBtnDebugger = QtWidgets.QToolButton(self.parent) self.stsBtnDebugger.setText(btnText) self.stsBtnDebugger.setToolTip(btnText) self.stsBtnDebugger.setAutoRaise(1) self.stsBtnDebugger.setMaximumHeight(18) StatusBar.addPermanentWidget(self.stsBtnDebugger, 0) self.stsBtnDebugger.clicked.connect(self.btnRedirector) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(btnIcon), QtGui.QIcon.Normal, QtGui.QIcon.On) self.stsBtnDebugger.setIcon(icon) else: self.stsBtnDebugger = None self.win.hide() # Plugin Lister #self.treeWidget.headerItem().setText(0, "DevS") self.treeWidget.itemDoubleClicked.connect(self.pluginSelected) self.treeWidget.setVisible(False) print('---------------------------------------') print('HaPy - Handy Python') print('Interactive Interpreter') print('---------------------------------------') print('Initiated!') print('\nLog Start Time: ' + str(strftime("%Y/%m/%d %H:%M:%S"))) print('\n---------------------------------------\n') print('*** Python %s on %s.***' % (sys.version, sys.platform)) print(sys.copyright) print('') print('Platform: ' + sys.platform) print('Version: ' + str(sys.getwindowsversion())) print('FileSys encodeing: ' + str(sys.getfilesystemencoding())) drline = "\n---------------------------------------\n" self.credit = drline + 'About HaPy:\nHandy Python - Interactive Interpreter/Scripting Environment \nAn expreimental project by \nKumaresan Lakshmanan\nFor Quick, Portable windows automation. \nDate: ' + last_update_date + drline print(self.credit) self.InitalizeScripts = InitalizeScripts self.scriptsDirName = ScriptsPath self.scriptsPath = os.path.abspath(self.scriptsDirName) print("Checking scripts path..." + os.path.abspath(self.scriptsPath)) if self.scriptsPath: if self.InitalizeScripts and self.scriptsPath and not os.path.exists( self.scriptsPath): os.makedirs(self.scriptsPath) else: print('Invalid script path!') #Start loading the scripts... try: self.execPlugin() self.treeWidget.setVisible(True) except: print(errorReport()) try: if self.InitalizeScripts: self.execStartUp() else: self.addEmptyTab() except: print(errorReport()) if self.standalone: self.qtConn.uiMain = self.win self.qtConn.installEventHandler() self.qtConn.addEventConnection(self.win, 'WindowDeactivate', self.onWinDeAct) self.qtConn.addEventConnection(self.win, 'Close', self.onClose) self.qtConn.addEventConnection(self.win, 'Hide', self.onHide) self.qtConn.addEventConnection(self.win, 'Show', self.onShow) if (os.path.exists('layout.lyt')): customList = self.qtTools.uiLayoutRestore( 'layout.lyt', [self.splitter, self.splitter_2]) if (customList): self.win.resize(customList[0]) self.win.move(customList[1]) self.loadTabs() print("All set, You are ready to go...") def onWinDeAct(self, *arg): #self.win.hide() pass def _handleTrayItemClicked(self, itemName): pass def trayItemClicked(self, *arg): caller = self.sender() itm = caller.text() if (itm == 'Quit'): sys.exit(0) if (itm == 'About'): print(self.credit) if (itm == 'Help'): print('Not Implemented') def trayAgentReady(self): """ trayagent(forwho,trayclickedfunction) catch the trayobj i trhough... Dont forget to kill your object on Close Event use... xtools.traykiller() """ self.tray = QtWidgets.QSystemTrayIcon( self.qtIcon.getIcon('action_log.png'), self.win) self.tray.activated.connect(self.trayClicked) #self.connect(self.tray,SIGNAL("activated(QSystemTrayIcon::ActivationReason)"),self.trayClicked) self.tray.show() return self.tray def trayClicked(self, click): if (click == 3): if (self.win.isVisible()): self.win.hide() else: self.win.show() #if self.win.windowState() == QtCore.Qt.WindowMinimized: self.win.setWindowState(QtCore.Qt.WindowActive) self.win.activateWindow() self.win.raise_() def traymessage(self, messagetitle, message): self.tray.showMessage(messagetitle, message) def traykiller(self): self.tray.hide() del (self.tray) def onClose(self, *arg): print("Closing...") self.traykiller() customList = [self.win.size(), self.win.pos()] self.qtTools.uiLayoutSave('layout.lyt', [self.splitter, self.splitter_2], customList) self.saveTabs() self.writeToLog() def onHide(self, *arg): #print("Hide") #self.win.setWindowFlags(QtCore.Qt.ToolTip) pass def onShow(self, *arg): #print("Show") #self.win.setWindowFlags(QtCore.Qt.Window) pass def saveTabs(self): lst = [] for cnt in range(0, self.tabWidget.count()): wdgt = self.tabWidget.widget(cnt) #'userSetup.py' lst.append(wdgt.toolTip()) current = self.tabWidget.currentIndex() lst.append(current) self.qtTools.quickSave(lst, "tabs.tbs") def loadTabs(self): if (os.path.exists('tabs.tbs')): lst = self.qtTools.quickLoad("tabs.tbs") for cnt in range(0, len(lst) - 1): if 'New Script' in lst[cnt]: self.addEmptyTab() elif 'userSetup.py' in lst[cnt]: continue else: if (os.path.exists(lst[cnt])): self.addNewTab(lst[cnt]) index = lst[len(lst) - 1] self.tabWidget.setCurrentIndex(index) def getUpdatedLocals(self): try: raise None except: frame = sys.exc_info()[2].tb_frame.f_back # evaluate commands in current namespace namespace = frame.f_globals.copy() namespace.update(frame.f_locals) return namespace def addShortcut(self, label='text', icon='bullet_star.png', callBackFn=None): if (text == '|'): self.toolbar2.addSeparator() else: action = QtWidgets.QAction(self) action.setText(label) if callBackFn is not None: action.triggered.connect(callBackFn) self.qtIcon.setIcon(action, icon) self.toolbar2.addAction(action) def setStandAloneModeFeatures(self): """ Standalone Mode :return: """ # Ready Menu Bar self.menubar = self.qtMenu.createMenuBar(self.win) self.mnuFile = self.qtMenu.createMenu(self.menubar, "File") self.mnuEdit = self.qtMenu.createMenu(self.menubar, "Edit") self.mnuRun = self.qtMenu.createMenu(self.menubar, "Run") self.mnuAbout = self.qtMenu.createMenu(self.menubar, "About") self.mnuFileNewScript = self.qtMenu.createMenuItem( self.win, self.mnuFile, "New Script", self.btnRedirector) self.qtMenu.createMenuItemSeperator(self.mnuFile) self.mnuFileLoadScript = self.qtMenu.createMenuItem( self.win, self.mnuFile, "Load Script", self.btnRedirector) self.mnuFileQuickSaveScript = self.qtMenu.createMenuItem( self.win, self.mnuFile, "Save Script", self.btnRedirector) self.mnuFileSaveScript = self.qtMenu.createMenuItem( self.win, self.mnuFile, "Save Script As", self.btnRedirector) self.qtMenu.createMenuItemSeperator(self.mnuFile) self.mnuFileQuit = self.qtMenu.createMenuItem(self.win, self.mnuFile, "Quit", self.btnRedirector) self.mnuEditClearOutput = self.qtMenu.createMenuItem( self.win, self.mnuEdit, "Clear Outputs", self.btnRedirector) self.mnuEditClearInput = self.qtMenu.createMenuItem( self.win, self.mnuEdit, "Clear Inputs", self.btnRedirector) # self.mnuRunExecuteNoClear = self.qtMenu.createMenuItem(self.win, self.mnuRun, "Execute Script + No Clear", self.execute_Clicked_NoClear) # self.mnuRunExecuteNoClear.setShortcut("Ctrl+Enter") self.mnuRunExecute = self.qtMenu.createMenuItem( self.win, self.mnuRun, "Execute Script", self.doExecute) self.mnuRunExecute.setShortcut("Ctrl+Enter") self.mnuAboutHPSE = self.qtMenu.createMenuItem(self.win, self.mnuAbout, "About HaPy", self.btnRedirector) self.qtIcon.setIcon(self.mnuFileNewScript, 'page.png') self.qtIcon.setIcon(self.mnuFileLoadScript, 'page_edit.png') self.qtIcon.setIcon(self.mnuFileQuickSaveScript, 'page_save.png') self.qtIcon.setIcon(self.mnuFileSaveScript, 'page_green.png') self.qtIcon.setIcon(self.mnuEditClearOutput, 'align_bellow.png') self.qtIcon.setIcon(self.mnuEditClearInput, 'align_above.png') self.qtIcon.setIcon(self.mnuRunExecute, 'page_lightning.png') self.qtIcon.setIcon(self.mnuAboutHPSE, 'emotion_happy.png') self.toolbar.addAction(self.mnuFileNewScript) self.toolbar.addSeparator() self.toolbar.addAction(self.mnuFileLoadScript) self.toolbar.addAction(self.mnuFileQuickSaveScript) self.toolbar.addSeparator() self.toolbar.addAction(self.mnuEditClearOutput) #self.toolbar.addAction(self.mnuEditClearInput) self.toolbar.addSeparator() self.toolbar.addAction(self.mnuRunExecute) #self.toolbar.addWidget(self.mnuFileLoadScript) self.tray = self.trayAgentReady() #self.rightMenu = self.qtMenu.createMenuForList(self, 'DevConsoleMenu', ['|','Help','About','|','Quit'], self.trayItemClicked) self.rightMenu = self.qtMenu.createMenu(None, 'DevConsoleMenu') self.tray.setContextMenu(self.rightMenu) self.updateTrayMenu('Quit', self.trayItemClicked) self.updateTrayMenu('|') self.updateTrayMenu('About', self.trayItemClicked) self.updateTrayMenu('Help', self.trayItemClicked) #self.setWindowFlags(QtCore.Qt.Tool) ''' # Remove other buttons self.btnClearOutput.setVisible(0) self.toolButton.setVisible(0) self.line_5.setVisible(0) self.line_6.setVisible(0) self.line_7.setVisible(0) self.btnLoadScript.setVisible(0) self.btnSaveScript.setVisible(0) self.line.setVisible(0) self.btnClearInput.setVisible(0) self.btnExecute.setVisible(0) self.line_2.setVisible(0) self.line_3.setVisible(0) self.line_4.setVisible(0) self.sciOutput.resize(self.sciOutput.width(), self.sciOutput.height() + 90) self.label.setText("Output:") self.label_2.setText("Workspace:") self.label_3.setText("Quick Commands:") ''' def updateTrayMenu(self, itemName, fnToCall=None): self.qtMenu.updateMenu(self, self.rightMenu, itemName, fnToCall) def pluginRightClick(self, point): #menu = ['m1','m2',['m3','m31',['m32','m321','m322'],'m33'],'m4','m5',['m6','m61','m62'],'m7'] #self.qtTools.popUpMenuAdv(menu,self.treeWidget,point,self.pluginRightClickSelected,'addedArgument') item = self.treeWidget.itemAt(point) if (item): name = item.text(0) path = item.data(0, QtCore.Qt.UserRole) if (os.path.exists(path)): if (os.path.isfile(path)): #Edit - File (If UI File there, Edit them) uiFile = item.data(0, QtCore.Qt.UserRole).replace( '.py', '.ui') if (os.path.exists(uiFile)): self.qtTools.popUpMenu(self.treeWidget, point, ["Edit", "Edit UI", "Delete"], self.pluginRightClickSelected, ["myarg1", "myarg2"]) else: self.qtTools.popUpMenu(self.treeWidget, point, ["Edit", "Delete"], self.pluginRightClickSelected, ["myarg1", "myarg2"]) else: #Directories - Nodes or Other dir if (name == "nodes"): self.qtTools.popUpMenu(self.treeWidget, point, ["New Node"], self.pluginRightClickSelected, ["myarg1", "myarg2"]) else: self.qtTools.popUpMenu(self.treeWidget, point, [ "New Simple Plug", "New UI Plug", "New Folder", "Refresh" ], self.pluginRightClickSelected, ["myarg1", "myarg2"]) else: #Empty area - right clicked or unknown path. self.qtTools.popUpMenu(self.treeWidget, point, [ "New Simple Plug", "New UI Plug", "New Folder", "Refresh" ], self.pluginRightClickSelected, ["myarg1", "myarg2"]) else: self.qtTools.popUpMenu( self.treeWidget, point, ["New Simple Plug", "New UI Plug", "New Folder", "Refresh"], self.pluginRightClickSelected, ["myarg1", "myarg2"]) def pluginRightClickSelected(self, *arg): act = self.parent.sender() menuOption = act.text() item = self.treeWidget.itemAt(act.data()) itemSelected = item.text(0) if item else None path = item.data(0, QtCore.Qt.UserRole) if item else self.scriptsPath if (menuOption == "Refresh"): self.execPlugin() if (menuOption == "New Folder"): nFolderName = self.qtTools.showInputBox( "ScriptFolderName", "Enter the new folder name", "folderName") if (nFolderName): newPath = os.path.join(path, nFolderName) os.makedirs(newPath, exist_ok=True) self.execPlugin() if (menuOption == "New Node"): nFileName = self.qtTools.showInputBox("ScriptName", "Enter the new Node name", "newNode") if (nFileName): data = self.ttls.fileContent('templateNode.py') data = data.replace('Add', nFileName.capitalize()) f = os.path.join(path, nFileName + ".py") self.ttls.writeFileContent(f, data) self.execPlugin() self.addNewTab(f) if (menuOption == "New Simple Plug"): nFileName = self.qtTools.showInputBox("PlugName", "Enter the new Plug name", "newPlug") if (nFileName): data = self.ttls.fileContent('templatePlug.py') data = data.replace('myClass', nFileName) f = os.path.join(path, nFileName + ".py") self.ttls.writeFileContent(f, data) self.execPlugin() self.addNewTab(f) if (menuOption == "New UI Plug"): nFileName = self.qtTools.showInputBox( "PlugName", "Enter the new UI Plug name", "newUIPlug") if (nFileName): pyf = os.path.join(path, nFileName + ".py") uif = os.path.join(path, nFileName + ".ui") data = self.ttls.fileContent('templateUIPlug.py') data = data.replace('UI_myUIPlug.ui', uif) data = data.replace('myUIPlug', nFileName) self.ttls.writeFileContent(pyf, data) self.execPlugin() self.addNewTab(pyf) data = self.ttls.fileContent('templateUIPlug.ui') self.ttls.writeFileContent(uif, data) print("Created..." + pyf) print("Created..." + uif) if (menuOption == "Edit"): pyFile = (item.data(0, QtCore.Qt.UserRole)) self.addNewTab(pyFile) if (menuOption == "Edit UI"): uiFile = item.data(0, QtCore.Qt.UserRole).replace('.py', '.ui') args = '"' + self.pyDesigner + '"' + " " + '"' + uiFile + '"' print("Execute: (" + args + ")") subprocess.call(args) if (menuOption == "Delete"): pyFile = item.data(0, QtCore.Qt.UserRole) uiFile = pyFile.replace('.py', '.ui') try: if (os.path.exists(pyFile)): print("Deleting..." + pyFile) os.remove(pyFile) if (os.path.exists(uiFile)): print("Deleting..." + uiFile) os.remove(uiFile) self.execPlugin() except OSError: pass def pluginSelected(self, *eve): selectedItem = eve[0] itemInfo = self.qtTree.getItemLabel(selectedItem) name = itemInfo['Label'] path = itemInfo['Data'] if (os.path.isfile(path)): print("\nExecuting: " + path) content = self.ttls.fileContent(path) self.runScript(content) def showAttrs(self, obj): dlg = QtWidgets.QDialog(self.win) dlg.setWindowTitle(str(type(obj))) lt = QtWidgets.QListWidget(dlg) for each in inspect.getmembers(obj): itm = QtWidgets.QListWidgetItem() attrName = str(each[0]) fnSymbol = "" if (inspect.isfunction(each[1]) or inspect.ismethod(each[1])): args = inspect.getargspec(each[1])[0] fnSymbol = "(" + str(args) + ")" itm.setText(attrName + fnSymbol) lt.addItem(itm) dlg.setFixedHeight(190) dlg.setFixedWidth(255) dlg.show() def execPlugin(self, *arg): self.populatePlugins() def populatePlugins(self): self.treeWidget.clear() print("Loading Plugins... ") spath = os.getcwd() if ('\.' in spath): return None self.addToSysPath(spath) for eachItem in os.listdir(self.scriptsPath): currentDirName = eachItem currentDirPath = os.path.join(self.scriptsPath, currentDirName) if (not "__" in currentDirPath): if os.path.isdir(currentDirPath): rItem = self.qtTree.createItem(currentDirName, currentDirPath) self.qtTree.addNewRoot(self.treeWidget, rItem) self.populatePluginsCore(rItem, currentDirPath) else: self.loadPlugin(currentDirPath) print("Plugins Loaded!") def populatePluginsCore(self, parentItem, searchPath): if ('\.' in searchPath): return None self.addToSysPath(searchPath) for eachItem in os.listdir(searchPath): currentDirName = eachItem currentDirPath = os.path.join(searchPath, currentDirName) if (not "__" in currentDirPath): if os.path.isdir(currentDirPath): rItem = self.qtTree.createItem(currentDirName, currentDirPath) self.qtTree.addChild(rItem, parentItem) self.populatePluginsCore(rItem, currentDirPath) else: self.loadPlugin(currentDirPath, parentItem) def addToSysPath(self, path): path = os.path.abspath(path) if ('\.' in path): return None print("Adding path to system... " + path) code = r'''import sys,os path2Add="%s" if path2Add not in sys.path and os.path.exists(path2Add): sys.path.append(path2Add) ''' % (path).replace(os.path.sep, '/') self.runScript(code) def loadPlugin(self, plugFile, parentTreeItem=None): if ('\.' in plugFile): return None modName = os.path.basename(plugFile).replace( os.path.splitext(plugFile)[1], '') content = self.ttls.fileContent(plugFile) expecting = "For DevConsole" if (expecting in content): item = self.qtTree.createItem(modName, plugFile) if (parentTreeItem is None): plugTreeItem = self.qtTree.addNewRoot(self.treeWidget, item) else: plugTreeItem = self.qtTree.addChild(item, parentTreeItem) print("Adding Plug... " + plugFile) else: print("Skipped Plug! (Add tag 'For DevConsole') " + plugFile) plugTreeItem = None #self.runScript(content) return plugTreeItem def execStartUp(self, *arg): self.addToSysPath(self.scriptsPath) self.userSetup = os.path.join(self.scriptsPath, 'userSetup.py') self.userSetup = self.userSetup if os.path.exists( self.userSetup) else os.path.join(self.scriptsPath, 'userSetup.pyc') self.userSetup = self.userSetup if os.path.exists( self.userSetup) else '' self.runScriptFile(self.userSetup) self.loadScriptCore(self.userSetup) def runScriptFile(self, scriptFile): if scriptFile and os.path.exists(scriptFile): print('Executing... %s' % scriptFile) data = self.ttls.fileContent(scriptFile) self.runScript(data) else: print('Script file missing...' + scriptFile) def encrypt(self, text): code = int(sys.argv[1] if (len(sys.argv) > 1) else 4321) cipher = '' for each in text: c = (ord(each) + code) % 126 if c < 32: c += 31 cipher += chr(c) return cipher def decrypt(self, text): code = int(sys.argv[1] if (len(sys.argv) > 1) else 4321) plaintext = '' for each in text: p = (ord(each) - code) % 126 if p < 32: p += 95 plaintext += chr(p) return plaintext def tabKeyPress(self, event): modifiers = QtWidgets.QApplication.keyboardModifiers() if (modifiers == QtCore.Qt.ControlModifier and event.key() == QtCore.Qt.Key_S): self.quickSave() if (modifiers == QtCore.Qt.ControlModifier and event.key() == QtCore.Qt.Key_N): self.addEmptyTab() #print(modifiers == QtCore.Qt.ControlModifier and event.key()==16777221) def tabClose(self, tabIndex): cnt = self.tabWidget.count() if (cnt > 1): #proceed closing the tab self.tabWidget.removeTab(tabIndex) def addEmptyTab(self): newTab = QtWidgets.QWidget() self.tabWidget.addTab(newTab, 'New Script') newTab.setToolTip('New Script') self.tabWidget.setCurrentWidget(newTab) tabGrid = QtWidgets.QGridLayout(newTab) tabGrid.setContentsMargins(2, 2, 2, 2) newSciInput = QsciScintilla(newTab) newSciInput.setFrameShape(QtWidgets.QFrame.Box) tabGrid.addWidget(newSciInput, 0, 0, 1, 1) self._setQSci(newSciInput) newSciInput.setText('') newSciInput.setFocus() def addNewTab(self, scriptFile): print("Loading tab..." + scriptFile) fileName = os.path.basename(scriptFile) newTab = QtWidgets.QWidget() self.tabWidget.addTab(newTab, fileName) newTab.setToolTip(scriptFile) self.tabWidget.setCurrentWidget(newTab) tabGrid = QtWidgets.QGridLayout(newTab) tabGrid.setContentsMargins(2, 2, 2, 2) newSciInput = QsciScintilla(newTab) newSciInput.setFrameShape(QtWidgets.QFrame.Box) tabGrid.addWidget(newSciInput, 0, 0, 1, 1) self._setQSci(newSciInput) data = str(self.ttls.fileContent(scriptFile)) newSciInput.setText(data) def _setQSci(self, newSciInput): newSciInput.setEolMode(Qsci.QsciScintilla.EolUnix) newSciInput.setAutoCompletionSource(Qsci.QsciScintilla.AcsAll) newSciInput.setLexer(self.PLX) newSciInput.setAutoCompletionThreshold(1) newSciInput.setAutoIndent(True) newSciInput.setIndentationsUseTabs(False) newSciInput.setAutoCompletionFillupsEnabled(True) newSciInput.setBraceMatching(Qsci.QsciScintilla.StrictBraceMatch) newSciInput.setMarginLineNumbers(1, 1) newSciInput.setMarginWidth(1, 45) newSciInput.setUtf8(True) newSciInput.setEolVisibility(False) #newSciInput.setWrapMode(Qsci.QsciScintilla.WrapMode(Qsci.QsciScintillaBase.SC_WRAP_WORD)) #newSciInput.setWrapVisualFlags(Qsci.QsciScintilla.WrapVisualFlag(Qsci.QsciScintilla.WrapFlagByBorder), Qsci.QsciScintilla.WrapVisualFlag(Qsci.QsciScintilla.WrapFlagNone), 0) def quickSave(self): (qsci, scriptName) = self.getCurrentEditor() if (scriptName != 'New Script'): self.saveQSCItoFile(qsci, scriptName) #self.qtTools.showInfoBox('Quick Save', 'File Saved!') print("Quick Saved! - " + str(scriptName)) else: self.saveScriptAs() def saveScriptAs(self): scpt = self.scriptsPath scpt = scpt if os.path.exists(scpt) else 'C:' options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName = QFileDialog.getSaveFileName(self.win, 'Save python script file...', scpt, 'Python(*.py);;All Files (*)', options=options) if (fileName and fileName[0] != ''): fileName = fileName[0] self.saveScriptCore(fileName) #Close and Reload Tab cin = self.tabWidget.currentIndex() self.tabClose(cin) self.loadScriptCore(fileName) def saveScriptCore(self, fileName): (qsci, scriptName) = self.getCurrentEditor() self.saveQSCItoFile(qsci, fileName) def saveQSCItoFile(self, qsci, fileName): self.ttls.writeFileContent(fileName, qsci.text()) def loadScript(self): scpt = self.scriptsPath scpt = scpt if os.path.exists(scpt) else 'D:' options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName = QFileDialog.getOpenFileName(self.win, 'Open python script file...', scpt, 'Python(*.py);;All Files (*)', options=options) if fileName and fileName[0] != '' and os.path.exists(fileName[0]): fileName = fileName[0] self.loadScriptCore(fileName) def loadScriptCore(self, fileName): if (os.path.isfile(fileName) and os.path.exists(fileName)): self.addNewTab(fileName) def btnRedirector(self): actingButton = self.parent.sender() scpt = self.scriptsPath scpt = scpt if os.path.exists(scpt) else 'D:' #if actingButton == self.toolButton: # self.treeWidget.setVisible(self.toolButton.isChecked()) if actingButton == self.stsBtnDebugger: if self.win.isVisible(): self.win.hide() else: self.win.show() elif (actingButton == self.btnNewScript or (self.standalone and actingButton == self.mnuFileNewScript)): self.addEmptyTab() elif ( actingButton == self.btnQuickSaveScript or (self.standalone and actingButton == self.mnuFileQuickSaveScript)): self.quickSave() # elif (actingButton == self.btnClearOutput or (self.standalone and actingButton == self.mnuEditClearOutput)): # self.sciOutput.clear() # self.loadedFileName = '' # self.loadedFile = False # self.lblFileLoadInfo.setText('No File Loaded!') elif (actingButton == self.btnExecute): self.doExecute() elif (actingButton == self.btnLoadScript or (self.standalone and actingButton == self.mnuFileLoadScript)): self.loadScript() elif (actingButton == self.btnSaveScript or (self.standalone and actingButton == self.mnuFileSaveScript)): self.saveScriptAs() elif (self.standalone and actingButton == self.mnuAboutHPSE): print(self.credit) elif (actingButton == self.mnuEditClearOutput): self.sciOutput.clear() elif (actingButton == self.mnuEditClearInput): (qsci, scriptName) = self.getCurrentEditor() qsci.clear() elif (self.standalone and actingButton == self.mnuFileQuit): sys.exit(0) else: print('Unkown button' + str(actingButton)) def getCurrentEditor(self): cwidget = self.tabWidget.currentWidget() lst = cwidget.children() if (len(lst) > 1): qsci = lst[1] scriptName = cwidget.toolTip() return (qsci, scriptName) def mouseLock(self): self.win.grabMouse(QtCore.Qt.WaitCursor) self.win.grabKeyboard() QtWidgets.QApplication.processEvents() def mouseRelease(self): self.win.releaseMouse() self.win.releaseKeyboard() QtWidgets.QApplication.processEvents() def doExecute(self): self.mouseLock() (qsci, scriptName) = self.getCurrentEditor() if (scriptName != ""): print("Executing..." + scriptName) if not str(qsci.text()) == '': inputs = str(qsci.text()).rstrip() self.appendPlainOutput(inputs) self.appendLineOutput() self.ABS.add(inputs) self.ABS.prepare() self.runScript(inputs) self.mouseRelease() """ ''' def runScript(self, script): try: command = str(script).replace('\r\n', '\n') try: #self.inter.compile(commands) res = eval(command, globals(), self.inter.locals) #res = exec(command, globals(), self.inter.locals) #print('Done1') except SyntaxError: # self.inter.showtraceback() # exec (command, globals(), locals()) res = self.inter.runcode(command) #print('Done2') QtWidgets.QApplication.processEvents() if res is not None: print(repr(res)) except SystemExit: self.inter.showsyntaxerror() crashHandle() sys.exit(0) except: print (errorReport()) ''' """ def runScript(self, script): try: command = str(script).replace('\r\n', '\n') locals = self.getUpdatedLocals() self.inter.locals.update(locals) try: res = self.inter.runcode(command) except SyntaxError: self.inter.showsyntaxerror() QtWidgets.QApplication.processEvents() if res is not None: print('\n---------------------------------------\n') print(repr(res)) print('\n---------------------------------------\n') except SystemExit: self.inter.showsyntaxerror() crashHandle() sys.exit(0) except: print(errorReport()) def appendPlainOutput(self, txt): self.appendTextCore(txt) def appendLineOutput(self): self.appendTextCore('\n') def appendSplOutput(self, txt): nowtime = strftime("%Y-%m-%d %H:%M:%S") splOutput = str(nowtime) + ' : ' + str(txt) self.appendPlainOutput(splOutput) def appendLog(self, txt): self.appendLineOutput() self.appendTextCore(txt) def appendTextCore(self, txt): self.sciOutput.setCursorPosition(self.sciOutput.lines(), 0) self.sciOutput.insert(str(txt)) vsb = self.sciOutput.verticalScrollBar() vsb.setValue(vsb.maximum()) hsb = self.sciOutput.horizontalScrollBar() hsb.setValue(0) # Standard Error and Print Capture def write(self, txt): self.appendPlainOutput(txt) def showEditor(self, exec_=0): if exec_: self.win.exec_() else: self.win.show() def writeToLog(self): """ Write info :return: """ curdir = os.getcwd() logdir = curdir + '/ConsoleLog' if not os.path.exists(logdir): os.makedirs(logdir) fileList = os.listdir(logdir) if len(fileList) >= self.logCount: fileToDelete = fileList[0] delFile = logdir + '/' + fileToDelete os.remove(delFile) print('\nLog End Time: ' + str(strftime("%Y/%m/%d %H:%M:%S"))) fileName = 'DC' + strftime("%Y%m%d%H%M%S") + '.log' logFileName = logdir + '/' + fileName self.saveQSCItoFile(self.sciOutput, logFileName)
def runcode(self, code): try: for line in self.buffer: m = self.regexpChareDefine.search(line) if m is not None: newChareTypeName = m.group(1) source = '\n'.join(self.buffer) charm.thisProxy.registerNewChareType(newChareTypeName, source, awaitable=True).get() if self.options.verbose > 0: self.write('Charm4py> Broadcasted Chare definition\n') return line = self.buffer[0] module_name = None if 'import' in line: m = self.regexpImport1.search(line) if m is not None: module_name = m.group(1) else: m = self.regexpImport2.match(line) if m is not None: module_name = m.group(1) if module_name is not None: prev_modules = set(sys.modules.keys()) InteractiveInterpreter.runcode(self, code) if module_name not in sys.modules: # error importing the module return if self.options.broadcast_imports: charm.thisProxy.rexec('\n'.join(self.buffer), awaitable=True).get() if self.options.verbose > 0: self.write('Charm4py> Broadcasted import statement\n') new_modules = set(sys.modules.keys()) - prev_modules chare_types = [] for module_name in new_modules: try: members = inspect.getmembers(sys.modules[module_name], inspect.isclass) except: # some modules can throw exceptions with inspect.getmembers, ignoring them for now continue for C_name, C in members: if C.__module__ != chare.__name__ and hasattr( C, 'mro'): if chare.ArrayMap in C.mro(): chare_types.append(C) elif Chare in C.mro(): chare_types.append(C) elif chare.Group in C.mro( ) or chare.Array in C.mro( ) or chare.Mainchare in C.mro(): raise Charm4PyError( 'Chares must not inherit from Group, Array or' ' Mainchare. Refer to new API') if len(chare_types) > 0: if self.options.broadcast_imports: charm.thisProxy.registerNewChareTypes( chare_types, awaitable=True).get() if self.options.verbose > 0: self.write( 'Broadcasted the following chare definitions: ' + str([str(C) for C in chare_types]) + '\n') else: self.write( 'Charm4py> ERROR: import module(s) contain Chare definitions but the import was not broadcasted\n' ) return except: self.showtraceback() self.interactive_running = True InteractiveInterpreter.runcode(self, code) self.interactive_running = False
class DevConsole(QtGui.QDialog, Ui_devConsole): ''' DevConsole Arguments:s ShowPrint... Captures all print outputs to DevConsole o/p ShowError... Captures all error info outputs to DevConsole o/p Methods: appendPlainOutput(txt) ... Append plain text into DevConsole o/p appendSplOutput(txt) ... Append TimeStamped text into DevConsole o/p ''' def __init__(self, parent=None, ShowPrint=True, ShowError=True, StatusBar=None, AsDock=False, SaveLogRefreshDays=30, ScriptsPath='Scripts/', InitalizeScripts=True): ''' Parent - Pass QWIDGET based objects. Else I will create my own. ShowPrint - Redirect standard prints ShowError - Redirect standard errors StatusBar - Attach DevC Invoke button to this status bar else You should invoke DevC explicitly AsDock - If True creates DevC as a dock else as a dialog window ''' if not parent: print 'No parent widget specified! Creating my own parent!' prn = QtGui.QWidget() prn.setObjectName('DevC') self.standalone = 1 else: prn = parent self.standalone = 0 if not hasattr(prn, 'addDockWidget') and not self.standalone: AsDock = False print 'Current parent does not support dock!' if ShowPrint: sys.stdout = self if ShowError: sys.stderr = self winObj = str(prn.objectName()) setattr(__builtin__, winObj if winObj else 'mainwin', prn) if AsDock: self.win = QtGui.QDockWidget(prn) base = QtGui.QWidget() self.setupUi(base) self.win.setWidget(base) prn.addDockWidget(QtCore.Qt.DockWidgetArea(2), self.win) else: self.win = QtGui.QDialog(prn) self.setupUi(self.win) self.parent = prn self.inter = InteractiveInterpreter() self.inter.locals['dev'] = self self.inter.locals['self'] = self.parent self.win.setWindowIcon(prn.windowIcon()) self.win.setWindowTitle('K Python Interpreter') self.PLX = Qsci.QsciLexerPython(self.win) self.ABS = Qsci.QsciAPIs(self.PLX) self.PLX.setAPIs(self.ABS) self.sciInput.setAutoCompletionSource(Qsci.QsciScintilla.AcsAll) self.sciInput.setLexer(self.PLX) self.sciInput.setAutoCompletionThreshold(1) self.sciInput.setAutoIndent(True) self.sciInput.setAutoCompletionFillupsEnabled(True) self.sciInput.setBraceMatching(Qsci.QsciScintilla.StrictBraceMatch) self.sciInput.setMarginLineNumbers(1, 1) self.sciInput.setMarginWidth(1, 45) self.sciOutput.setReadOnly(1) self.sciOutput.setAutoCompletionSource(Qsci.QsciScintilla.AcsAll) self.sciOutput.setLexer(self.PLX) self.sciOutput.setAutoCompletionThreshold(1) self.sciOutput.setAutoIndent(True) self.sciOutput.setAutoCompletionFillupsEnabled(True) self.sciOutput.setBraceMatching(Qsci.QsciScintilla.StrictBraceMatch) self.sciOutput.setMarginLineNumbers(1, 1) self.sciOutput.setMarginWidth(1, 45) #Connections self.parent.connect(self.btnClearInput, QtCore.SIGNAL('clicked()'), self.btnRedirector) self.parent.connect(self.btnClearOutput, QtCore.SIGNAL('clicked()'), self.btnRedirector) self.parent.connect(self.btnExecute, QtCore.SIGNAL('clicked()'), self.btnRedirector) self.parent.connect(self.btnLoadScript, QtCore.SIGNAL('clicked()'), self.btnRedirector) self.parent.connect(self.btnSaveScript, QtCore.SIGNAL('clicked()'), self.btnRedirector) self.parent.connect(self.cline, QtCore.SIGNAL('returnPressed()'), self.commandLineExecute) if StatusBar: self.stsBtnDebugger = QtGui.QToolButton() self.stsBtnDebugger.setText('DevConsole') self.stsBtnDebugger.setToolTip('DevConsole') self.stsBtnDebugger.setAutoRaise(1) self.stsBtnDebugger.setMaximumHeight(18) StatusBar.addPermanentWidget(self.stsBtnDebugger, 0) self.parent.connect(self.stsBtnDebugger, QtCore.SIGNAL('clicked()'), self.btnRedirector) else: self.stsBtnDebugger = None self.win.hide() print 'Simple Python Scripting Environment (SPSE)' print '--------------------------------' print 'Initiated!' print '\nLog Start Time: ' + str(strftime("%Y/%m/%d %H:%M:%S")) print '\n---------------------------------------\n' print '*** Python %s on %s.***' % (sys.version, sys.platform) print sys.copyright print '' print 'Platform: ' + sys.platform print 'Version: ' + str(sys.getwindowsversion()) print 'FileSys encodeing: ' + str(sys.getfilesystemencoding()) print '\n---------------------------------------\n' self.credit = '\n---------------------------------------\nAbout Python Interactive Interpreter! \nExpreimental Feature developed by \nL.Kumaresan \nFor ABX Studios\n---------------------------------------\n ' self.InitalizeScripts = InitalizeScripts self.SaveLogRefreshDays = SaveLogRefreshDays self.scriptPath = ScriptsPath if self.scriptPath: if self.InitalizeScripts and self.scriptPath and not os.path.exists( self.scriptPath): os.makedirs(self.scriptPath) else: print 'Invalid script path!' try: if self.InitalizeScripts: self.execStartUp() except: print errorReport() print 'Error on startup' def __del__(self): self.saveLog() def execStartUp(self, *arg): #General Script: spath = os.getcwd() spath1 = self.scriptPath spath2 = spath + '/' + spath1 paths = [ '\nmodulePathList.append("' + spath + '")' '\nmodulePathList.append("' + spath1 + '")' '\nmodulePathList.append("' + spath2 + '")' ] paths = '\n'.join(paths) general = '''import sys import os modulePathList = [] %s for modulePath in modulePathList: modulePath = os.path.normpath(modulePath) if modulePath not in sys.path and os.path.exists(modulePath): sys.path.append(modulePath) ''' % (paths) self.runScript(general) print 'Accessing startup script folder... %s' % self.scriptPath if self.scriptPath: self.userSetup = os.path.join(self.scriptPath, 'userSetup.py') self.userSetup = self.userSetup if os.path.exists( self.userSetup) else os.path.join(self.scriptPath, 'userSetup.pyc') self.userSetup = self.userSetup if os.path.exists( self.userSetup) else '' if self.userSetup and os.path.exists(self.userSetup): f = open(self.userSetup, 'r') data = str(f.read()) f.close() self.sciInput.clear() self.sciInput.setText(data) print 'Parsing startup scripts...' self.runScript(data) else: print 'No Startup script file!' else: print 'No Startup script folder!' def commandLineExecute(self): if not str(self.cline.text()) == '': inputs = str(self.cline.text()).rstrip() self.appendPlainOutput(inputs) self.appendLineOutput() self.runScript(inputs) self.cline.setText('') def btnRedirector(self): actingButton = self.parent.sender() if actingButton == self.stsBtnDebugger: if self.win.isVisible(): self.win.hide() else: self.win.show() if actingButton == self.btnClearInput: self.sciInput.clear() if actingButton == self.btnClearOutput: self.sciOutput.clear() if actingButton == self.btnExecute: self.execute_Clicked() if actingButton == self.btnLoadScript: scpt = self.scriptPath scpt = scpt if os.path.exists(scpt) else 'D:' fileName = QtGui.QFileDialog.getOpenFileName( self.parent, 'Open python script file...', scpt, 'All Files (*)') if os.path.exists(fileName): f = open(fileName, 'r') data = str(f.read()) f.close() self.sciInput.clear() self.sciInput.setText(data) if actingButton == self.btnSaveScript: fileName = QtGui.QFileDialog.getSaveFileName( self.parent, 'Open python script file...', 'D:', 'All Files (*)') f = open(fileName + '.py', 'w') f.write(str(self.sciInput.text())) f.close() def execute_Clicked(self): if not str(self.sciInput.text()) == '': inputs = str(self.sciInput.text()).rstrip() self.appendPlainOutput(inputs) self.appendLineOutput() self.runScript(inputs) self.sciInput.setText('') def runScript(self, script): try: inputs = str(script).replace('\r\n', '\n') self.inter.runcode(inputs) except: print errorReport() def appendPlainOutput(self, txt): text = str(self.sciOutput.text()) text += txt self.sciOutput.setText(text) text = str(self.sciOutput.text()) vsb = self.sciOutput.verticalScrollBar() vsb.setValue(vsb.maximum()) def appendLineOutput(self): text = str(self.sciOutput.text()) text += '\n' self.sciOutput.setText(text) text = str(self.sciOutput.text()) vsb = self.sciOutput.verticalScrollBar() vsb.setValue(vsb.maximum()) def appendSplOutput(self, txt): nowtime = strftime("%Y-%m-%d %H:%M:%S") splOutput = str(nowtime) + ' : ' + str(txt) self.appendPlainOutput(splOutput) def appendLog(self, txt): self.appendLineOutput() text = str(self.sciOutput.text()) text += txt self.sciOutput.setText(text) text = str(self.sciOutput.text()) vsb = self.sciOutput.verticalScrollBar() vsb.setValue(vsb.maximum()) #Standard Error and Print Capture def write(self, txt): self.appendPlainOutput(txt) vsb = self.sciOutput.verticalScrollBar() vsb.setValue(vsb.maximum()) def showEditor(self, exec_=0): if exec_: self.win.exec_() else: self.win.show() def saveLog(self): curdir = os.getcwd() logdir = curdir + '/ConsoleLog' if not os.path.exists(logdir): os.makedirs(logdir) fileList = os.listdir(logdir) if len(fileList) == self.SaveLogRefreshDays: fileToDelete = fileList[0] delFile = logdir + '/' + fileToDelete os.remove(delFile) print '\nLog End Time: ' + str(strftime("%Y/%m/%d %H:%M:%S")) fileName = 'EVELOG' + strftime("%Y%m%d%H%M%S") + '.log' logFileName = logdir + '/' + fileName data = str(self.sciOutput.text()) fs = open(logFileName, 'w') fs.write(data) fs.close()
def run_code_button_clicked(self): interpreter = InteractiveInterpreter() interpreter.runcode(self.text.text())