def toString(self, structure): filename = '<input>' symbol = 'single' localVars = {"self": structure, "RETURN": ""} inter = InteractiveInterpreter(localVars) #if isinstance(source, types.UnicodeType): # import IOBinding # try: # source = source.encode(IOBinding.encoding) # except UnicodeError: console = InteractiveConsole(localVars, filename) try: code_object = compile(self.data, '<string>', 'exec') exec code_object in localVars except Exception as e: print("- ERR --Kind:%s---------------------------------------" % (self.template.kind)) InteractiveInterpreter.showsyntaxerror(console, filename) frames = inspect.trace() lineNumber = frames[1][2] print "At line %s" % lineNumber print("- /ERR -----------------------------------------") print("- CODE -----------------------------------------") lines = self.data.split('\n') for i in range(0, lineNumber): print lines[i] print "^" * 20 print("- /CODE -----------------------------------------") print("") return localVars["RETURN"]
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( code: str, stdout: Optional[TextIO] = None, stderr: Optional[TextIO] = None, namespace: Optional[Dict] = None, ) -> Optional[str]: """Execute a code.""" should_return_value = stdout is None if should_return_value: stdout = StringIO() if stderr is None: stderr = stdout if namespace is None: namespace = {} with redirect_output(stdout=stdout, stderr=stderr): InteractiveInterpreter(locals=namespace).runcode(code) if should_return_value: if stderr == stdout: return stdout.getvalue() return "\n".join([stderr.getvalue(), stdout.getvalue()]) return None
def __init__(self, parent=None): super(PythonWidget, self).__init__(parent) # PythonWidget attributes. self.locals = dict(__name__='__console__', __doc__=None) self.interpreter = InteractiveInterpreter(self.locals) # PythonWidget protected attributes. self._buffer = StringIO() self._bracket_matcher = BracketMatcher(self._control) self._call_tip_widget = CallTipWidget(self._control) self._completion_lexer = CompletionLexer(PythonLexer()) self._hidden = False self._highlighter = PythonWidgetHighlighter(self) self._last_refresh_time = 0 # file-like object attributes. self.encoding = sys.stdin.encoding # Configure the ConsoleWidget. self.tab_width = 4 self._set_continuation_prompt('... ') # Configure the CallTipWidget. self._call_tip_widget.setFont(self.font) self.font_changed.connect(self._call_tip_widget.setFont) # Connect signal handlers. document = self._control.document() document.contentsChange.connect(self._document_contents_change) # Display the banner and initial prompt. self.reset()
def __init__(self, parent=None): super(MyWindow, self).__init__(parent=parent) self.newshell = True self.stmt = True self.construct = False self.initUI() self.index = 0 self.interpreter = InteractiveInterpreter()
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
def __init__(self, parent=None): super(PyConsoleTextEdit, self).__init__(parent) self._interpreter_locals = {} self._interpreter = InteractiveInterpreter(self._interpreter_locals) self._comment_writer.write('Python %s on %s\n' % (sys.version.replace('\n', ''), sys.platform)) self._comment_writer.write('Qt bindings: %s version %s\n' % (QT_BINDING, QT_BINDING_VERSION)) self._add_prompt()
def eval_(self, request, context): result = '' try: expression = request.expression self.redirect_out() InteractiveInterpreter(globals()).runsource( expression, '<console>', 'single') result = self.reset_out() except Exception as e: logger.error(e) return updatestub_pb2.EvalResponse(result=str(result), returncode="SUCCESS")
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 __init__(self, Interpreter=None, Parent=None, OldInstance=None): # Variables self.Parent = Parent self.HistoryCount = 0 self.state = None self.BackState = None if OldInstance != None: self.Submodels = OldInstance.Submodels else: self.Submodels = [] for i in range(ButtonBehaviour_MDL.StateNum): self.Submodels.append(None) self.history = [] for i in range(ButtonBehaviour_MDL.StateNum): self.history.append(None) # Constructor for i in range(ButtonBehaviour_MDL.StateNum): self.history[i] = History() self.history[i].States = [] self.history[i].Times = [] for j in range(ButtonBehaviour_MDL.StateNum): self.history[i].States.append(-1) self.history[i].Times.append(-1) self.TimedTransitions = [] # used only when --ext is set for i in range(ButtonBehaviour_MDL.StateNum): self.TimedTransitions.append(None) self.clearEnteredStates() self.HasInteractor = 0 # Interpreter of action code if self.Parent == None: # Top-level model if Interpreter: self.DefaultInterpreter = Interpreter else: self.DefaultInterpreter = InteractiveInterpreter() self.setupInterpreter() ##self.EventsCond=threading.Condition() ##self.SchedulerCond=threading.Condition() self.Schedules = [] self.PendingEvents = None self.PendingEventsTail = None else: self.DefaultInterpreter = Interpreter self.Started = 0 self.Stopped = 0 self.description = ButtonBehaviour_MDL.Description
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 __init__(self): ''' Constructor ''' settingsLib.settings.__init__(self, None) widgetsLib.dynamicObjs.__init__(self, None) saftyLib.cryption.__init__(self, self) 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.inter = InteractiveInterpreter() self.inter.locals['dev'] = self globals()['dev'] = self
def __init__(self, Interpreter=None): # Variables self.state=None self.Submodels=[] for i in range(behaviour_generated_no_link_with_gui.StateNum): self.Submodels.append(None) self.history=[] for i in range(behaviour_generated_no_link_with_gui.StateNum): self.history.append(None) self.TimedTransitions=[] # used only when --pyext is set for i in range(behaviour_generated_no_link_with_gui.StateNum): self.TimedTransitions.append(None) self.clearEnteredStates() # Constructor for i in range(behaviour_generated_no_link_with_gui.StateNum): self.history[i]=History() self.history[i].States=[] self.history[i].Times=[] for j in range(behaviour_generated_no_link_with_gui.StateNum): self.history[i].States.append(-1) self.history[i].Times.append(-1) # Interpreter of action code if Interpreter: self.DefaultInterpreter=Interpreter else: self.DefaultInterpreter=InteractiveInterpreter() self.HasInteractor=0 self.setupInterpreter() self.Started=0 self.EventsLock=thread.allocate_lock() self.PendingEvents=None self.PendingEventsTail=None self.HandleEventRunning=0 self.description=behaviour_generated_no_link_with_gui.Description
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 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 main(): """ Print lines of input along with output. """ source_lines = (line.rstrip() for line in sys.stdin) console = InteractiveInterpreter() source = '' try: while True: source = next(source_lines) print('>>>', source) more = console.runsource(source) while more: next_line = next(source_lines) print('...', next_line) source += '\n' + next_line more = console.runsource(source) except StopIteration: if more: print('... ') more = console.runsource(source + '\n')
def main(): """ Print lines of input along with output. """ source_lines = (line.rstrip() for line in sys.stdin) console = InteractiveInterpreter() console.runsource('import graphlab') source = '' try: while True: source = source_lines.next() more = console.runsource(source) while more: next_line = source_lines.next() print '...', next_line source += '\n' + next_line more = console.runsource(source) except StopIteration: if more: print '... ' more = console.runsource(source + '\n')
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 main(): """ Print lines of input along with output. """ source_lines = (line.rstrip() for line in sys.stdin) console = InteractiveInterpreter() console.runsource("import turicreate") source = "" try: while True: source = source_lines.next() more = console.runsource(source) while more: next_line = source_lines.next() print "...", next_line source += "\n" + next_line more = console.runsource(source) except StopIteration: if more: print "... " more = console.runsource(source + "\n")
def runStartupCommands(self, locals): interp = InteractiveInterpreter(locals) """Execute the startup commands that import default modules""" interp.runsource("import os") interp.runsource("import sys") interp.runsource("import wx") interp.runsource("import vtk") interp.runsource("import numpy") interp.runsource("np = numpy") interp.runsource("import coda") interp.runsource("import harp") interp.runsource("import visan") interp.runsource("import visan.math") interp.runsource("from visan.commands import *") self.version = interp.locals['visan'].VERSION self.component_versions = [ "Python %d.%d.%d" % (sys.version_info[0], sys.version_info[1], sys.version_info[2]), "wxPython %s" % interp.locals['wx'].VERSION_STRING, "VTK %s" % interp.locals['vtk'].VTK_VERSION, "NumPy %s" % interp.locals['numpy'].__version__, "CODA %s" % interp.locals['coda'].version(), "HARP %s" % interp.locals['harp'].version(), ]
def __init__(self, shell_locals: List[ShellVariable]): self._shell_locals = shell_locals self._interpreter = InteractiveInterpreter()
import freeOrionAIInterface as fo from freeorion_tools import chat_human from code import InteractiveInterpreter from cStringIO import StringIO import sys interpreter = InteractiveInterpreter({'fo': fo}) debug_mode = False RED = '<rgba 255 0 0 255>%s</rgba>' WHITE = '<rgba 255 255 255 255>%s</rgba>' ENTERING_DEBUG_MESSAGE = 'Entering debug mode' def handle_debug_chat(sender, message): global debug_mode human_id = [x for x in fo.allPlayerIDs() if fo.playerIsHost(x)][0] ais = [x for x in fo.allPlayerIDs() if not fo.playerIsHost(x)] is_debug_chat = False if message == ENTERING_DEBUG_MESSAGE: is_debug_chat = True if sender != human_id: return is_debug_chat # don't chat with bots elif message == 'stop': is_debug_chat = True if debug_mode: chat_human("exiting debug mode") debug_mode = False elif debug_mode: print '>', message, is_debug_chat = True
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...")
# IN THE SOFTWARE. """ An interactive tutorial of pml's basic functionality. @author: drusk """ import platform from code import InteractiveInterpreter from subprocess import call from pml.api import * # Passing globals() to interpreter gives it access to the pml api imported # above. tutorial_interpreter = InteractiveInterpreter(globals()) def get_tutorial_lessons(): """ Returns: lessons: dict Keys are the names of lessons, the value is the function which will start the lesson. """ return { "datasets": lesson_dataset_intro, "classifiers": lesson_classifiers, "decision_trees": lesson_decision_trees, "pca": lesson_pca, "clustering": lesson_clustering
def __init__(self, *args: Any, **kwargs: Any) -> None: super(Module, self).__init__(*args, **kwargs) self._event = threading.Event() self._workload: Optional[Workload] = None self._health: Dict[str, Dict[str, Any]] = {} self._repl = InteractiveInterpreter(dict(mgr=self))
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'
from Tkinter import Tk from TrafficLightGUI import TrafficLightGUI from TrafficLightBehaviour import TrafficLightBehaviour from code import InteractiveInterpreter if __name__ == "__main__": # Create an interpreter with the current scope and dictionary # All the action code and guards are executed with this interpreter interpreter = InteractiveInterpreter(locals()) behaviour = TrafficLightBehaviour(interpreter) root = Tk() # Initialize the GUI with the behaviour model as a parameter # (see GUI.py) gui = TrafficLightGUI(behaviour, root) # Be sure to initialize the behaviour model after gui is created behaviour.initModel() # The Tkinter main event loop root.mainloop()
def run(): inp = sys.stdin.read() print ">>>", inp InteractiveInterpreter().runsource(inp)
def __init__(self): self.interpreter = InteractiveInterpreter()