コード例 #1
0
ファイル: pyshell.py プロジェクト: wangdyna/wxPython
    def __init__(self, parent, ID, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0,
                 locals=None, properties=None, banner=None):
        stc.StyledTextCtrl.__init__(self, parent, ID, pos, size, style)
        InteractiveInterpreter.__init__(self, locals)

        self.lastPromptPos = 0

        # the line cache is used to cycle through previous commands
        self.lines = []
        self.lastUsedLine = self.curLine = 0

        # set defaults and then deal with any user defined properties
        self.props = {}
        self.props.update(_default_properties)
        if properties:
            self.props.update(properties)
        self.UpdateProperties()

        # copyright/banner message
        if banner is None:
            self.write("Python %s on %s\n" % #%s\n(%s)\n" %
                       (sys.version, sys.platform,
                        #sys.copyright, self.__class__.__name__
                        ))
        else:
            self.write("%s\n" % banner)

        # write the initial prompt
        self.Prompt()

        # Event handlers
        self.Bind(wx.EVT_KEY_DOWN, self.OnKey)
        self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI, id=ID)
コード例 #2
0
ファイル: interpreter.py プロジェクト: chemscobra/sim42
 def __init__(self, locals=None, rawin=None, \
              stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr):
     """Create an interactive interpreter object."""
     InteractiveInterpreter.__init__(self, locals=locals)
     self.stdin = stdin
     self.stdout = stdout
     self.stderr = stderr
     if rawin:
         import __builtin__
         __builtin__.raw_input = rawin
         del __builtin__
     copyright = \
         'Type "copyright", "credits" or "license" for more information.'
     self.introText = 'Python %s on %s%s%s' % \
                      (sys.version, sys.platform, os.linesep, copyright)
     try:
         sys.ps1
     except AttributeError:
         sys.ps1 = '>>> '
     try:
         sys.ps2
     except AttributeError:
         sys.ps2 = '... '
     self.more = 0
     # List of lists to support recursive push().
     self.commandBuffer = []
     self.startupScript = os.environ.get('PYTHONSTARTUP')
コード例 #3
0
ファイル: pythonInterpreter.py プロジェクト: mplanck/USD
    def showtraceback(self):
        self._outputBrush = QtGui.QBrush(QtGui.QColor('#ff0000'))

        try:
            InteractiveInterpreter.showtraceback(self)
        finally:
            self._outputBrush = None
コード例 #4
0
 def __init__(self, tkconsole):
     self.tkconsole = tkconsole
     locals = sys.modules['__main__'].__dict__
     InteractiveInterpreter.__init__(self, locals=locals)
     self.save_warnings_filters = None
     self.restarting = False
     self.subprocess_arglist = self.build_subprocess_arglist()
コード例 #5
0
    def __init__(
        self, locals=None, rawin=None, stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr, showInterpIntro=True
    ):
        """Create an interactive interpreter object."""
        InteractiveInterpreter.__init__(self, locals=locals)
        self.stdin = stdin
        self.stdout = stdout
        self.stderr = stderr
        if rawin:
            import __builtin__

            __builtin__.raw_input = rawin
            del __builtin__
        if showInterpIntro:
            copyright = 'Type "help", "copyright", "credits" or "license"'
            copyright += " for more information."
            self.introText = "Python %s on %s%s%s" % (sys.version, sys.platform, os.linesep, copyright)
        try:
            sys.ps1
        except AttributeError:
            sys.ps1 = ">>> "
        try:
            sys.ps2
        except AttributeError:
            sys.ps2 = "... "
        self.more = 0
        # List of lists to support recursive push().
        self.commandBuffer = []
        self.startupScript = None
コード例 #6
0
 def showtraceback(self):
     "Extend base class method to reset output properly"
     self.tkconsole.resetoutput()
     self.checklinecache()
     InteractiveInterpreter.showtraceback(self)
     if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
         self.tkconsole.open_stack_viewer()
コード例 #7
0
 def __init__(self, localAndGlobalDict):
     self.stdin = None
     self.buf = ""
     InteractiveInterpreter.__init__(self, localAndGlobalDict)
     sys.ps1 = ""
     sys.ps2 = ""
     self.more = False
コード例 #8
0
 def __init__(self,
              locals=None,
              rawin=None,
              stdin=sys.stdin,
              stdout=sys.stdout,
              stderr=sys.stderr,
              showInterpIntro=True):
     """Create an interactive interpreter object."""
     InteractiveInterpreter.__init__(self, locals=locals)
     self.stdin = stdin
     self.stdout = stdout
     self.stderr = stderr
     if rawin:
         from six.moves import builtins
         builtins.raw_input = rawin
         del builtins
     if showInterpIntro:
         copyright = 'Type "help", "copyright", "credits" or "license"'
         copyright += ' for more information.'
         self.introText = 'Python %s on %s%s%s' % \
                          (sys.version, sys.platform, os.linesep, copyright)
     try:
         sys.ps1
     except AttributeError:
         sys.ps1 = '>>> '
     try:
         sys.ps2
     except AttributeError:
         sys.ps2 = '... '
     self.more = 0
     # List of lists to support recursive push().
     self.commandBuffer = []
     self.startupScript = None
コード例 #9
0
ファイル: pythonInterpreter.py プロジェクト: mplanck/USD
    def showsyntaxerror(self, filename = None):
        self._outputBrush = QtGui.QBrush(QtGui.QColor('#ffcc63'))

        try:
            InteractiveInterpreter.showsyntaxerror(self, filename)
        finally:
            self._outputBrush = None
コード例 #10
0
ファイル: pythonInterpreter.py プロジェクト: zloop1982/USD
    def showtraceback(self):
        self._outputBrush = QtGui.QBrush(QtGui.QColor('#ff0000'))

        try:
            InteractiveInterpreter.showtraceback(self)
        finally:
            self._outputBrush = None
コード例 #11
0
    def showsyntaxerror(self, filename=None):
        """Extend base class method: Add Colorizing

        Color the offending position instead of printing it and pointing at it
        with a caret.

        """
        text = self.tkconsole.text
        stuff = self.unpackerror()
        if stuff:
            msg, lineno, offset, line = stuff
            if lineno == 1:
                pos = "iomark + %d chars" % (offset - 1)
            else:
                pos = "iomark linestart + %d lines + %d chars" % (lineno - 1, offset - 1)
            text.tag_add("ERROR", pos)
            text.see(pos)
            char = text.get(pos)
            if char and char in IDENTCHARS:
                text.tag_add("ERROR", pos + " wordstart", pos)
            self.tkconsole.resetoutput()
            self.write("SyntaxError: %s\n" % str(msg))
        else:
            self.tkconsole.resetoutput()
            InteractiveInterpreter.showsyntaxerror(self, filename)
        self.tkconsole.showprompt()
コード例 #12
0
ファイル: pythonInterpreter.py プロジェクト: zloop1982/USD
    def showsyntaxerror(self, filename=None):
        self._outputBrush = QtGui.QBrush(QtGui.QColor('#ffcc63'))

        try:
            InteractiveInterpreter.showsyntaxerror(self, filename)
        finally:
            self._outputBrush = None
コード例 #13
0
 def __init__(self, localAndGlobalDict):
     self.stdin = None
     self.buf = ""
     InteractiveInterpreter.__init__(self, localAndGlobalDict)
     sys.ps1 = ""
     sys.ps2 = ""
     self.more = False
コード例 #14
0
ファイル: interpreter.py プロジェクト: douzujun/priithon
 def __init__(self,
              locals=None,
              rawin=None,
              stdin=sys.stdin,
              stdout=sys.stdout,
              stderr=sys.stderr):
     """Create an interactive interpreter object."""
     InteractiveInterpreter.__init__(self, locals=locals)
     self.stdin = stdin
     self.stdout = stdout
     self.stderr = stderr
     if rawin:
         import __builtin__
         __builtin__.raw_input = rawin
         del __builtin__
     #seb copyright = 'Type "help", "copyright", "credits" or "license"'
     #seb copyright += ' for more information.'
     #seb self.introText = 'Python %s on %s%s%s' % \
     #seb                  (sys.version, sys.platform, os.linesep, copyright)
     try:
         sys.ps1
     except AttributeError:
         sys.ps1 = '>>> '
     try:
         sys.ps2
     except AttributeError:
         sys.ps2 = '... '
     self.more = 0
     # List of lists to support recursive push().
     self.commandBuffer = []
     self.startupScript = os.environ.get('PYTHONSTARTUP')
コード例 #15
0
ファイル: rmt_interpreter.py プロジェクト: rainfiel/lua-crust
    def __init__(self, locals=None, rawin=None, 
                 stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr,
                 showInterpIntro=True):
        """Create an interactive interpreter object."""
        if not locals:
            locals = {}
        locals['connect'] = self.connect
        InteractiveInterpreter.__init__(self, locals=locals)
        self.lua_locals = {}
        self.stdin = stdin
        self.stdout = stdout
        self.stderr = stderr
        if rawin:
            import __builtin__
            __builtin__.raw_input = rawin
            del __builtin__
        if showInterpIntro:
            self.introText = 'Inspect the ejoy2dx client'
        try:
            sys.ps1
        except AttributeError:
            sys.ps1 = '>>> '
        try:
            sys.ps2
        except AttributeError:
            sys.ps2 = '... '
        self.more = 0
        # List of lists to support recursive push().
        self.commandBuffer = []
        self.startupScript = None

        self.socket = None
コード例 #16
0
ファイル: generate.py プロジェクト: jchome/CI-Generator
	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.encode('ascii','ignore'), '<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"]
コード例 #17
0
ファイル: py_console_text_edit.py プロジェクト: daju1-ros/rqt
class PyConsoleTextEdit(ConsoleTextEdit):
    _color_stdin = Qt.darkGreen
    _multi_line_char = ':'
    _multi_line_indent = '    '
    _prompt = ('>>> ', '... ')  # prompt for single and multi line
    exit = Signal()

    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 update_interpreter_locals(self, newLocals):
        self._interpreter_locals.update(newLocals)

    def _exec_code(self, code):
        try:
            self._interpreter.runsource(code)
        except SystemExit:  # catch sys.exit() calls, so they don't close the whole gui
            self.exit.emit()
コード例 #18
0
ファイル: interactive.py プロジェクト: sdrave/charm4py
    def __init__(self, args):
        global Charm4PyError
        from .charm import Charm4PyError
        # restore original tty stdin and stdout (else readline won't work correctly)
        os.dup2(charm.origStdinFd, 0)
        os.dup2(charm.origStoutFd, 1)
        charm.dynamic_register['future'] = future_
        charm.dynamic_register['self'] = self
        InteractiveInterpreter.__init__(self, locals=charm.dynamic_register)
        self.filename = '<console>'
        self.resetbuffer()
        # regexp to detect when user defines a new chare type
        self.regexpChareDefine = re.compile(
            'class\s*(\S+)\s*\(.*Chare.*\)\s*:')
        # regexps to detect import statements
        self.regexpImport1 = re.compile('\s*from\s*(\S+) import')
        self.regexpImport2 = re.compile('import\s*(\S+)')
        self.options = charm.options.interactive

        try:
            import readline
            import rlcompleter
            readline.parse_and_bind('tab: complete')
        except:
            pass

        try:
            sys.ps1
        except AttributeError:
            sys.ps1 = '>>> '
        try:
            sys.ps2
        except AttributeError:
            sys.ps2 = '... '
        self.thisProxy.start()
コード例 #19
0
ファイル: myinterp.py プロジェクト: neffmallon/pistol
 def __init__(self):
     self.stdout = sys.stdout
     self.stderr = sys.stderr
     self.out_cache = FileCacher()
     self.err_cache = FileCacher()
     InteractiveInterpreter.__init__(self)
     return
コード例 #20
0
 def showtraceback(self):
     "Extend base class method to reset output properly"
     self.tkconsole.resetoutput()
     self.checklinecache()
     InteractiveInterpreter.showtraceback(self)
     if self.tkconsole.getvar("<<toggle-jit-stack-viewer>>"):
         self.tkconsole.open_stack_viewer()
コード例 #21
0
    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()
コード例 #22
0
 def __init__(self, tkconsole):
     self.tkconsole = tkconsole
     locals = sys.modules['__main__'].__dict__
     InteractiveInterpreter.__init__(self, locals=locals)
     self.save_warnings_filters = None
     self.restarting = False
     self.subprocess_arglist = self.build_subprocess_arglist()
コード例 #23
0
    def showsyntaxerror(self, filename=None):
        """Extend base class method: Add Colorizing

        Color the offending position instead of printing it and pointing at it
        with a caret.

        """
        text = self.tkconsole.text
        stuff = self.unpackerror()
        if stuff:
            msg, lineno, offset, line = stuff
            if lineno == 1:
                pos = "iomark + %d chars" % (offset - 1)
            else:
                pos = "iomark linestart + %d lines + %d chars" % \
                      (lineno-1, offset-1)
            text.tag_add("ERROR", pos)
            text.see(pos)
            char = text.get(pos)
            if char and char in IDENTCHARS:
                text.tag_add("ERROR", pos + " wordstart", pos)
            self.tkconsole.resetoutput()
            self.write("SyntaxError: %s\n" % str(msg))
        else:
            self.tkconsole.resetoutput()
            InteractiveInterpreter.showsyntaxerror(self, filename)
        self.tkconsole.showprompt()
コード例 #24
0
ファイル: developerconsole.py プロジェクト: Joelone/IsisWorld
 def command(self, text):
   if not self.hidden:
     self.cscroll = None
     self.command = ''
     self.entry.set('')
     self.entry['focus'] = True
     self.writeOut(self.otext['text'] + ' ' + text + '\n', False)
     if text != '' and (len(self.commands) == 0 or self.commands[-1] != text):
       self.commands.append(text)
     
     # Insert plugins into the local namespace
     locals = __main__.__dict__
     #locals['manager'] = self.manager
     #for plugin in self.manager.named.keys():
     #  locals[plugin] = self.manager.named[plugin]
     locals['panda3d'] = panda3d
     
     # Run it and print the output.
     if not self.initialized:
       InteractiveInterpreter.__init__(self, locals = locals)
       self.initialized = True
     try:
       if self.runsource(self.block + '\n' + text) and text != '':
         self.otext['text'] = '.'
         self.block += '\n' + text
       else:
         self.otext['text'] = ':'
         self.block = ''      
     except Exception: # Not just "except", it will also catch SystemExit
       # Whoops! Print out a traceback.
       self.writeErr(traceback.format_exc())
コード例 #25
0
ファイル: pyshell.py プロジェクト: AceZOfZSpades/RankPanda
    def __init__(self, parent, ID, pos=wx.DefaultPosition,
                 size=wx.DefaultSize, style=0,
                 locals=None, properties=None, banner=None):
        stc.StyledTextCtrl.__init__(self, parent, ID, pos, size, style)
        InteractiveInterpreter.__init__(self, locals)

        self.lastPromptPos = 0

        # the line cache is used to cycle through previous commands
        self.lines = []
        self.lastUsedLine = self.curLine = 0

        # set defaults and then deal with any user defined properties
        self.props = {}
        self.props.update(_default_properties)
        if properties:
            self.props.update(properties)
        self.UpdateProperties()

        # copyright/banner message
        if banner is None:
            self.write("Python %s on %s\n" % #%s\n(%s)\n" %
                       (sys.version, sys.platform,
                        #sys.copyright, self.__class__.__name__
                        ))
        else:
            self.write("%s\n" % banner)

        # write the initial prompt
        self.Prompt()

        # Event handlers
        self.Bind(wx.EVT_KEY_DOWN, self.OnKey)
        self.Bind(stc.EVT_STC_UPDATEUI, self.OnUpdateUI, id=ID)
コード例 #26
0
ファイル: SunShell.py プロジェクト: mikeMcoder/myRepository
 def __init__(self, locals=None, rawin=None, \
              stdin=sys.stdin, stdout=sys.stdout, stderr=sys.stderr):
     """Create an interactive interpreter object."""
     InteractiveInterpreter.__init__(self, locals=locals)
     self.stdin = stdin
     self.stdout = stdout
     self.stderr = stderr
     if rawin:
         import __builtin__
         __builtin__.raw_input = rawin
         del __builtin__
     self.introText = 'SunShell %s %s\n' % (VERSION, COPYRIGHT)
     self.introText += 'Use "it.connect()" to establish a connection.\n'
     try:
         sys.ps1
     except AttributeError:
         sys.ps1 = '>>> '
     try:
         sys.ps2
     except AttributeError:
         sys.ps2 = '... '
     self.more = 0
     # List of lists to support recursive push().
     self.commandBuffer = []
     self.startupScript = os.environ.get('PYTHONSTARTUP')
コード例 #27
0
class PyConsoleTextEdit(ConsoleTextEdit):
    _color_stdin = Qt.darkGreen
    _multi_line_char = ':'
    _multi_line_indent = '    '
    _prompt = ('>>> ', '... ')  # prompt for single and multi line
    exit = Signal()

    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 update_interpreter_locals(self, newLocals):
        self._interpreter_locals.update(newLocals)

    def _exec_code(self, code):
        try:
            self._interpreter.runsource(code)
        except SystemExit:  # catch sys.exit() calls, so they don't close the whole gui
            self.exit.emit()
コード例 #28
0
ファイル: interpreter.py プロジェクト: usbalex/pyqtconsole
 def __init__(self, stdin, stdout, locals=None):
     QObject.__init__(self)
     InteractiveInterpreter.__init__(self, locals)
     self.locals['exit'] = Exit()
     self.stdin = stdin
     self.stdout = stdout
     self._executing = False
     self.compile = partial(compile_multi, self.compile)
コード例 #29
0
    def showtraceback(self):
        type_, value, tb = sys.exc_info()
        self.stdout.write('\n')

        if type_ == KeyboardInterrupt:
            self.stdout.write('KeyboardInterrupt\n')
        else:
            InteractiveInterpreter.showtraceback(self)
コード例 #30
0
ファイル: helpers.py プロジェクト: JamesHowlett99/TekVeb
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()}
コード例 #31
0
ファイル: shell.py プロジェクト: anirudhb/ma_desktop
 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()
コード例 #32
0
 def __init__(self, tkconsole):
     self.tkconsole = tkconsole
     locals = sys.modules['__main__'].__dict__
     InteractiveInterpreter.__init__(self, locals=locals)
     self.save_warnings_filters = None
     self.restarting = False
     self.subprocess_arglist = None
     self.original_compiler_flags = self.compile.compiler.flags
コード例 #33
0
    def __init__(self, app):
        InteractiveInterpreter.__init__(
            self,
            vdict({
                "app": app,
                "plot": plot.plot
            },
                  setitem=self.setitem,
                  delitem=self.delitem))

        self.frame = tk.Frame(app,
                              padx=16,
                              pady=8,
                              background=Color.DARK_BLACK)

        Text.__init__(self,
                      self.frame,
                      readonly=True,
                      background=Color.DARK_BLACK,
                      font=FONT,
                      padx=0,
                      pady=0,
                      wrap="word",
                      cursor="arrow",
                      insertbackground=Color.DARK_BLACK)

        sys.displayhook = self.write
        sys.excepthook = self.showtraceback
        __builtins__["print"] = self.write
        __builtins__["help"] = Help(app)
        __builtins__["clear"] = Clear(self)
        __builtins__[
            "copyright"] = "Copyright (c) 2018-2021 Matt Calhoun.\nAll Rights Reserved."
        __builtins__[
            "credits"] = "Created by Matt Calhoun.\nSee https://mathinspector.com for more information."
        __builtins__["license"] = License()

        self.app = app
        self.prompt = Prompt(self, self.frame)
        self.parse = CodeParser(app)
        self.buffer = []
        self.prevent_module_import = False

        self.bind("<Key>", self._on_key_log)
        self.bind("<Configure>", self.prompt.on_configure_log)
        self.bind("<ButtonRelease-1>", self.on_click_log)
        self.pack(fill="both", expand=True)

        for i in ["error_file"]:
            self.tag_bind(i,
                          "<Motion>",
                          lambda event, key=i: self._motion(event, key))
            self.tag_bind(i,
                          "<Leave>",
                          lambda event, key=i: self._leave(event, key))
            self.tag_bind(i,
                          "<Button-1>",
                          lambda event, key=i: self._click(event, key))
コード例 #34
0
    def __init__(self, element):
        InteractiveInterpreter.__init__(self)
        self.element = element
        self.buffer = ''
        self.stream = DOMInterpreter.Stream(self)
        self.source = []

        self.write('pyglet interpreter\n')
        self.write('>>> ')
コード例 #35
0
ファイル: helpers.py プロジェクト: JamesHowlett99/TekVeb
 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
コード例 #36
0
 def __init__(self, queue, local={}):
     if '__name__' not in local:
         local['__name__'] = '__console__'
     if '__doc__' not in local:
         local['__doc__'] = None
     self.out_queue = queue
     sys.stdout = DummyFile('stdout', queue)
     sys.stderr = DummyFile('sdterr', queue)
     InteractiveInterpreter.__init__(self, locals=local)
コード例 #37
0
    def __init__(self, element):
        InteractiveInterpreter.__init__(self)
        self.element = element
        self.buffer = ''
        self.stream = DOMInterpreter.Stream(self)
        self.source = []

        self.write('pyglet interpreter\n')
        self.write('>>> ')
コード例 #38
0
ファイル: interpreter.py プロジェクト: jamescasbon/codenode
    def __init__(self, namespace=None):
        if namespace is not None:
            namespace = namespace()

        InteractiveInterpreter.__init__(self, namespace)
        self.output_trap = OutputTrap()
        self.completer = Completer(self.locals)
        self.input_count = 0
        self.interrupted = False
コード例 #39
0
ファイル: interpreter.py プロジェクト: AEliu/calibre
 def __init__(self, queue, local={}):
     if '__name__' not in local:
         local['__name__'] = '__console__'
     if '__doc__' not in local:
         local['__doc__'] = None
     self.out_queue = queue
     sys.stdout = DummyFile('stdout', queue)
     sys.stderr = DummyFile('sdterr', queue)
     InteractiveInterpreter.__init__(self, locals=local)
コード例 #40
0
ファイル: interpreter.py プロジェクト: yingjun2/codenode
    def __init__(self, namespace=None):
        if namespace is not None:
            namespace = namespace()

        InteractiveInterpreter.__init__(self, namespace)
        self.output_trap = OutputTrap()
        self.completer = Completer(self.locals)
        self.input_count = 0
        self.interrupted = False
コード例 #41
0
ファイル: pyshell.py プロジェクト: emilyemorehouse/ast-and-me
 def __init__(self, tkconsole):
     self.tkconsole = tkconsole
     locals = sys.modules['__main__'].__dict__
     InteractiveInterpreter.__init__(self, locals=locals)
     self.save_warnings_filters = None
     self.restarting = False
     self.subprocess_arglist = None
     self.port = PORT
     self.original_compiler_flags = self.compile.compiler.flags
コード例 #42
0
    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()
コード例 #43
0
ファイル: ConsoleWindow.py プロジェクト: dacut/ret
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
コード例 #44
0
 def execfile(self, filename, source=None):
     # Execute an existing file
     if source is None:
         source = open(filename, "r").read()
     try:
         code = compile(source, filename, "exec")
     except (OverflowError, SyntaxError):
         self.tkconsole.resetoutput()
         InteractiveInterpreter.showsyntaxerror(self, filename)
     else:
         self.runcode(code)
コード例 #45
0
ファイル: PyShell.py プロジェクト: alexei-matveev/ccp1gui
 def execfile(self, filename, source=None):
     # Execute an existing file
     if source is None:
         source = open(filename, "r").read()
     try:
         code = compile(source, filename, "exec")
     except (OverflowError, SyntaxError):
         self.tkconsole.resetoutput()
         InteractiveInterpreter.showsyntaxerror(self, filename)
     else:
         self.runcode(code)
コード例 #46
0
ファイル: shell.py プロジェクト: anirudhb/ma_desktop
class MyWindow(QtGui.QWidget):
    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 initUI(self):
        self.sh = QtGui.QTextEdit(
            '''
Python 2.7.6 on linux2
** DO NOT DELETE SHELL PROMPT! **
>>> ''', self)
        self.sh.textChanged.connect(self.shellop)
        self.sh.setReadOnly(True)
        self.sh.setReadOnly(False)

    def shellop(self):
        self.index += 1
        if self.sh.toPlainText()[self.index] == "\n" and self.sh.toPlainText()[
                self.index - 1] == ":":
            self.stmt = False
            self.construct = True
        elif self.sh.toPlainText()[self.index] == "\n" and not self.construct:
            self.stmt = not self.stmt

            class stdoutProxy:
                def write(self, s):
                    self.sh.insertPlainText(s)

            stdout = sys.stdout
            sys.stdout = stdoutProxy()
            self.interpreter.runsource(self.sh.toPlainText())
            self.sh.insertPlainText("\n")
            self.index += 1
            while self.interpreter.showtraceback():
                print self.interpreter.showtraceback()
            sys.stdout = stdout
        if self.sh.toPlainText()[
                self.index] == "\n" and not self.construct and not self.stmt:
            self.stmt = not self.stmt
            self.sh.insertPlainText(">>> ")
            self.index += 4
        if self.construct and self.sh.toPlainText(
        )[self.index] == "\n" and self.sh.toPlainText()[self.index - 1] == " ":
            self.construct = False
            self.sh.insertPlainText(">>> ")
            self.index += 4
        if self.construct:
            self.sh.insertPlainText("... ")
            index += 4
コード例 #47
0
 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)
コード例 #48
0
ファイル: kaap_childshell.py プロジェクト: DaveMcEwan/kaap
 def __init__(self, local={}):
     self.stdout = sys.stdout
     self.stdout_cache = FileCacher()
     self.stderr = sys.stderr
     self.stderr_cache = FileCacher()
     
     # Define minimum local variables to sub shell.
     if '__name__' not in local: local['__name__'] = '__kaap__'
     if '__doc__' not in local: local['__doc__'] = None
     
     InteractiveInterpreter.__init__(self, local)
     return
コード例 #49
0
ファイル: FullRunner.py プロジェクト: fredokun/MrPython
    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
コード例 #50
0
    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
コード例 #51
0
ファイル: interpreter.py プロジェクト: vertrex/DFF
    def __init__(self, parent=None, log=''):
        QTextEdit.__init__(self, parent)
        InteractiveInterpreter.__init__(self, None)
        self.setupUi(self)
        self.name = self.windowTitle()
        self.log = log or ''
        self.__canwrite = True

        if parent is None:
            self.eofKey = Qt.Key_D
        else:
            self.eofKey = None

        self.line = QString()
        self.lines = []
        self.point = 0
        self.more = 0
        self.reading = 0
        self.history = []
        self.pointer = 0
        self.cursor_pos = 0
        self.fgcolor = QColor("white")
        self.selcolor = QColor("green")
        self.strcolor = QColor("red")

        self.redirect = RedirectIO()
        self.sig = "IIputtext(QString)"
        self.connect(self, SIGNAL(self.sig),
                     self.sputtext)  #, Qt.QueuedConnection)
        self.connect(self, SIGNAL("Iputtext(QString)"), self.puttext)
        self.redirect.addparent(
            self,
            ["dff.ui.gui.widget.interpreter", "code", "__console__", "pydoc"])

        self.ps1 = ">>> "
        self.ps2 = "... "
        self.writePrompt()
        api_imports = [
            "from dff.api.types.libtypes import Variant, VList, VMap, DateTime, typeId, Argument, Parameter, ConfigManager, Constant, Config, Path",
            "from dff.api.vfs.vfs import vfs",
            "from dff.api.vfs.libvfs import VFS, FileMapping, ABSOLUTE_ATTR_NAME, RELATIVE_ATTR_NAME",
            "from dff.api.filters.libfilters import Filter",
            "from dff.api.search.libsearch import Search",
            "from dff.api.events.libevents import EventHandler, event",
            "from dff.api.datatype.libdatatype import DataTypeManager, DataTypeHandler",
            "from dff.api.loader.loader import loader",
            "from dff.api.module.module import Module, Script",
            "from dff.api.taskmanager.taskmanager import TaskManager"
        ]
        for api_import in api_imports:
            self.more = self.runsource(api_import)
コード例 #52
0
ファイル: console.py プロジェクト: igui/sdf-showcase
	def __init__(self, console_widget, locals = {}):
	
		self.__console_widget = console_widget
			
		self.__ps1 = ">>> " 
		self.__ps2 = "... "
		self.__ps = self.__ps1
		self.__partial_source = ""
		
		# se encarga de ejecutar los comandos
		self.__command_procesor = ItemProcesorPipeline(1)
		
		self.__locals = self.__init_locals(locals)
		InteractiveInterpreter.__init__(self, locals)
コード例 #53
0
ファイル: glumoldebugger.py プロジェクト: lebauce/artub
 def execfile(self, filename, source=None):
     "Execute an existing file"
     if source is None:
         source = open(filename, "r").read()
     try:
         code = compile(source, filename, "exec")
     except (OverflowError, SyntaxError):
         #self.tkconsole.resetoutput()
         tkerr = sys.stderr
         print>>tkerr, '*** Error in script or command!\n'
         print>>tkerr, 'Traceback (most recent call last):'
         InteractiveInterpreter.showsyntaxerror(self, filename)
     else:
         self.runcode(code)
コード例 #54
0
ファイル: spcmd.py プロジェクト: skada/splunk-appframework
 def __init__(self, **kwargs):
     self.service = client.connect(**kwargs)
     self.delete = self.service.delete
     self.get = self.service.get
     self.post = self.service.post
     locals = {
         'service': self.service,
         'connect': client.connect,
         'delete': self.delete,
         'get': self.get,
         'post': self.post,
         'load': self.load,
     }
     InteractiveInterpreter.__init__(self, locals)
コード例 #55
0
 def __init__(self, tkconsole):
 
     self.tkconsole = tkconsole # Required by later rpc registrations.
     
     self.active_seq = None
     self.port = 8833
     self.rpcclt = None
     self.rpcpid = None
     
     locals = sys.modules['__main__'].__dict__
     InteractiveInterpreter.__init__(self, locals=locals)
     self.save_warnings_filters = None
     self.restarting = False
 
     self.subprocess_arglist = self.build_subprocess_arglist()
コード例 #56
0
ファイル: __init__.py プロジェクト: vlegoff/tsunami
    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
コード例 #57
0
ファイル: shell.py プロジェクト: anirudhb/ma_desktop
class MyWindow(QtGui.QWidget):
    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 initUI(self):
        self.sh = QtGui.QTextEdit('''
Python 2.7.6 on linux2
** DO NOT DELETE SHELL PROMPT! **
>>> ''', self)
        self.sh.textChanged.connect(self.shellop)
        self.sh.setReadOnly(True)
        self.sh.setReadOnly(False)

    def shellop(self):
        self.index += 1
        if self.sh.toPlainText()[self.index] == "\n" and self.sh.toPlainText()[self.index-1] == ":":
            self.stmt = False
            self.construct = True
        elif self.sh.toPlainText()[self.index] == "\n" and not self.construct:
            self.stmt = not self.stmt
            class stdoutProxy:
                def write(self, s):
                    self.sh.insertPlainText(s)
            stdout = sys.stdout
            sys.stdout = stdoutProxy()
            self.interpreter.runsource(self.sh.toPlainText())
            self.sh.insertPlainText("\n")
            self.index += 1
            while self.interpreter.showtraceback():
                print self.interpreter.showtraceback()
            sys.stdout = stdout
        if self.sh.toPlainText()[self.index] == "\n" and not self.construct and not self.stmt:
            self.stmt = not self.stmt
            self.sh.insertPlainText(">>> ")
            self.index += 4
        if self.construct and self.sh.toPlainText()[self.index] == "\n" and self.sh.toPlainText()[self.index-1] == " ":
            self.construct = False
            self.sh.insertPlainText(">>> ")
            self.index += 4
        if self.construct:
            self.sh.insertPlainText("... ")
            index += 4
コード例 #58
0
ファイル: interpreter.py プロジェクト: halbbob/dff
    def __init__(self, parent=None, log=""):
        QTextEdit.__init__(self, parent)
        InteractiveInterpreter.__init__(self, None)
        self.setupUi(self)
        self.name = self.windowTitle()
        self.log = log or ""
        self.__canwrite = True

        if parent is None:
            self.eofKey = Qt.Key_D
        else:
            self.eofKey = None

        self.line = QString()
        self.lines = []
        self.point = 0
        self.more = 0
        self.reading = 0
        self.history = []
        self.pointer = 0
        self.cursor_pos = 0
        self.fgcolor = QColor("white")
        self.selcolor = QColor("green")
        self.strcolor = QColor("red")

        self.redirect = RedirectIO()
        self.sig = "Iputtext"
        self.connect(self, SIGNAL(self.sig), self.puttext)
        self.redirect.addparent(self, ["ui.gui.widget.interpreter", "code", "__console__", "pydoc"])

        self.ps1 = ">>> "
        self.ps2 = "... "
        self.writePrompt()
        api_imports = [
            "from api.types.libtypes import Variant, VList, VMap, vtime, typeId, Argument, Parameter, ConfigManager, Constant, Config, Path",
            "from api.vfs.vfs import vfs",
            "from api.vfs.libvfs import VFS, FileMapping, ABSOLUTE_ATTR_NAME, RELATIVE_ATTR_NAME",
            "from api.filters.libfilters import Filter",
            "from api.search.libsearch import Search",
            "from api.events.libevents import EventHandler, event",
            "from api.datatype.libdatatype import DataTypeManager, DataTypeHandler",
            "from api.loader.loader import loader",
            "from api.module.module import Module, Script",
            "from api.magic.libmagichandler import MagicType, MimeType",
            "from api.taskmanager.taskmanager import TaskManager",
        ]
        for api_import in api_imports:
            self.more = self.runsource(api_import)
コード例 #59
0
ファイル: python_shell.py プロジェクト: robmcmullen/pyface
    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()