Python code.compile_command() Examples

The following are 10 code examples of code.compile_command(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module code , or try the search function .
Example #1
Source File: Recording.py    From swirlypy with GNU General Public License v3.0 6 votes vote down vote up
def compile_ast(self, source, filename = "<input>", symbol = "single"):
        # Here, we try to compile the relevant code. It may throw an
        # exception indicating that the command is not complete, in
        # which case we cannot proceed, but a full command will be
        # supplied eventually.
        compiled = code.compile_command(source, filename, symbol)
        # If the compilation succeeded, as indicated by its object not being
        # None, and no exception having occurred, parse it with AST and
        # store that.
        if compiled != None:
            self.latest_parsed = ast.parse(source, filename, symbol)
            CaptureExprs().visit(self.latest_parsed)
            # Since latest_parsed has been altered to capture values computed
            # but not assigned, store an unaltered copy for testing.
            self.clean_parsed = ast.parse(source, filename, symbol)
            
            return compile(self.latest_parsed, filename, symbol) 
Example #2
Source File: shell.py    From rssant with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def runsource(self, source):
        if not source:
            return False
        try:
            code_obj = compile_command(source)
        except (SyntaxError, ValueError, OverflowError):
            traceback.print_exc()
            return False
        if code_obj is None:
            return True
        response = self.client.request('eval', source=source)
        if response.content:
            self.write(response.content)
        return False 
Example #3
Source File: __main__.py    From luci-py with Apache License 2.0 5 votes vote down vote up
def CMDshell(args):
  """Starts a shell with api.* in.."""
  logging_utils.prepare_logging(None)
  logging_utils.set_console_level(logging.DEBUG)

  from bot_code import bot_main
  from api import os_utilities
  from api import platforms
  local_vars = {
      'bot_main': bot_main,
      'json': json,
      'os_utilities': os_utilities,
      'platforms': platforms,
  }
  # Can't use: from api.platforms import *
  local_vars.update(
      (k, v) for k, v in platforms.__dict__.items()
      if not k.startswith('_'))

  if args:
    for arg in args:
      exec code.compile_command(arg) in local_vars
  else:
    code.interact('Locals:\n  ' + '\n  '.join(sorted(local_vars)), None,
                  local_vars)
  return 0 
Example #4
Source File: gtk2manhole.py    From python-for-android with Apache License 2.0 5 votes vote down vote up
def key_Return(self, entry, event):
        text = self.getText()
        # Figure out if that Return meant "next line" or "execute."
        try:
            c = code.compile_command(text)
        except SyntaxError, e:
            # This could conceivably piss you off if the client's python
            # doesn't accept keywords that are known to the manhole's
            # python.
            point = buffer.get_iter_at_line_offset(e.lineno, e.offset)
            buffer.place(point)
            # TODO: Componentize!
            self.toplevel.output.append(str(e), "exception") 
Example #5
Source File: gtk2manhole.py    From BitTorrent with GNU General Public License v3.0 5 votes vote down vote up
def key_Return(self, entry, event):
        text = self.getText()
        # Figure out if that Return meant "next line" or "execute."
        try:
            c = code.compile_command(text)
        except SyntaxError, e:
            # This could conceivably piss you off if the client's python
            # doesn't accept keywords that are known to the manhole's
            # python.
            point = buffer.get_iter_at_line_offset(e.lineno, e.offset)
            buffer.place(point)
            # TODO: Componentize!
            self.toplevel.output.append(str(e), "exception") 
Example #6
Source File: pipeline.py    From daudin with MIT License 4 votes vote down vote up
def _tryExec(self, command, print_):
        self._debug('Trying to compile %r.' % (command,))

        exception = None

        try:
            codeobj = compile_command(command)
        except (OverflowError, SyntaxError, ValueError) as e:
            self._debug('%s: %s.' % (e.__class__.__name__, e))
            if self.printTracebacks:
                self._debug(traceback.format_exc())
            self.pendingText = ''
            exception = e
        else:
            self._debug('Command compiled OK.')
            so = StringIO()
            if codeobj:
                self.local['_'] = self.stdin
                with newStdout(so):
                    try:
                        exec(codeobj, self.local)
                    except Exception as e:
                        self._debug('Could not exec: %s.' % e)
                        if self.printTracebacks:
                            self._debug(traceback.format_exc())
                        exception = e
                    else:
                        self._debug('Exec succeeded.')
                self.pendingText = ''
            else:
                self._debug('Incomplete command.')
                self.pendingText = command

        if exception is None:
            if self.pendingText:
                print_ = False
            else:
                stdout = so.getvalue()
                if stdout:
                    self._debug('Exec printed %r.' % (stdout,))
                    if stdout.endswith('\n'):
                        stdout = stdout[:-1]
                    if stdout.find('\n') > -1:
                        self.lastStdin = self.stdin
                        self.stdin = stdout.split('\n')
                        self.lastResultIsList = True
                    else:
                        self.lastStdin = self.stdin
                        self.stdin = stdout
                else:
                    print_ = False

            return True, print_
        else:
            return False, False 
Example #7
Source File: pydevconsole.py    From PyDev.Debugger with Eclipse Public License 1.0 4 votes vote down vote up
def console_exec(thread_id, frame_id, expression, dbg):
    """returns 'False' in case expression is partially correct
    """
    frame = dbg.find_frame(thread_id, frame_id)

    is_multiline = expression.count('@LINE@') > 1
    expression = str(expression.replace('@LINE@', '\n'))

    # Not using frame.f_globals because of https://sourceforge.net/tracker2/?func=detail&aid=2541355&group_id=85796&atid=577329
    # (Names not resolved in generator expression in method)
    # See message: http://mail.python.org/pipermail/python-list/2009-January/526522.html
    updated_globals = {}
    updated_globals.update(frame.f_globals)
    updated_globals.update(frame.f_locals)  # locals later because it has precedence over the actual globals

    if IPYTHON:
        need_more = exec_code(CodeFragment(expression), updated_globals, frame.f_locals, dbg)
        if not need_more:
            pydevd_save_locals.save_locals(frame)
        return need_more

    interpreter = ConsoleWriter()

    if not is_multiline:
        try:
            code = compile_command(expression)
        except (OverflowError, SyntaxError, ValueError):
            # Case 1
            interpreter.showsyntaxerror()
            return False
        if code is None:
            # Case 2
            return True
    else:
        code = expression

    # Case 3

    try:
        Exec(code, updated_globals, frame.f_locals)

    except SystemExit:
        raise
    except:
        interpreter.showtraceback()
    else:
        pydevd_save_locals.save_locals(frame)
    return False


#=======================================================================================================================
# main
#======================================================================================================================= 
Example #8
Source File: PythonConsole.py    From deprecated-binaryninja-python with GNU General Public License v2.0 4 votes vote down vote up
def process_input(self):
		self.input_history += [str(self.input.text())]
		self.input_history_pos = None

		input = str(self.input.text()) + "\n"
		self.input.setText("")

		self.output.textCursor().movePosition(QTextCursor.End)
		fmt = QTextCharFormat()
		fmt.setForeground(QBrush(Qt.black))
		if len(self.prompt.text()) > 0:
			self.output.textCursor().insertText(self.prompt.text() + " " + input, fmt)
		else:
			self.output.textCursor().insertText(input, fmt)
		self.output.ensureCursorVisible()

		if self.input_requested:
			# Request for data from stdin
			self.input_requested = False
			self.input.setEnabled(False)
			self.input_result = input
			self.input_event.set()
			return

		if self.source is not None:
			self.source = self.source + input
			if input != "\n":
				# Don't end multiline input until a blank line
				return
			input = self.source

		try:
			result = code.compile_command(input)
		except:
			result = False

		if result is None:
			if self.source is None:
				self.source = input
			else:
				self.source += input
			self.prompt.setText("...")
			return

		self.source = None
		self.prompt.setText(">>>")

		self.thread.code = input
		self.thread.event.set()
		self.running = True

		self.thread.done.wait(0.05)
		if self.thread.done.is_set():
			self.thread.done.clear()
			self.running = False
		else:
			self.input.setEnabled(False) 
Example #9
Source File: pywidgets.py    From BitTorrent with GNU General Public License v3.0 4 votes vote down vote up
def processKey(self, entry, event):
        # TODO: make key bindings easier to customize.

        stopSignal = False
        # ASSUMPTION: Assume Meta == mod4
        isMeta = event.state & gtk.GDK.MOD4_MASK
        if event.keyval == gtk.GDK.Return:
            isShift = event.state & gtk.GDK.SHIFT_MASK
            if isShift:
                self.linemode = True
                self.insert_defaults('\n')
            else:
                stopSignal = True
                text = self.get_chars(0,-1)
                if not text: return
                try:
                    if text[0] == '/':
                        # It's a local-command, don't evaluate it as
                        # Python.
                        c = True
                    else:
                        # This will tell us it's a complete expression.
                        c = code.compile_command(text)
                except SyntaxError, e:
                    # Ding!
                    self.set_positionLineOffset(e.lineno, e.offset)
                    print "offset", e.offset
                    errmsg = {'traceback': [],
                              'exception': [str(e) + '\n']}
                    self.toplevel.output.console([('exception', errmsg)])
                except OverflowError, e:
                    e = traceback.format_exception_only(OverflowError, e)
                    errmsg = {'traceback': [],
                              'exception': e}
                    self.toplevel.output.console([('exception', errmsg)])
                else:
                    if c is None:
                        self.linemode = True
                        stopSignal = False
                    else:
                        self.sendMessage(entry)
                        self.clear() 
Example #10
Source File: pydevconsole.py    From filmkodi with Apache License 2.0 4 votes vote down vote up
def console_exec(thread_id, frame_id, expression):
    """returns 'False' in case expression is partially correct
    """
    frame = pydevd_vars.find_frame(thread_id, frame_id)

    expression = str(expression.replace('@LINE@', '\n'))

    #Not using frame.f_globals because of https://sourceforge.net/tracker2/?func=detail&aid=2541355&group_id=85796&atid=577329
    #(Names not resolved in generator expression in method)
    #See message: http://mail.python.org/pipermail/python-list/2009-January/526522.html
    updated_globals = {}
    updated_globals.update(frame.f_globals)
    updated_globals.update(frame.f_locals) #locals later because it has precedence over the actual globals

    if IPYTHON:
        return exec_code(CodeFragment(expression), updated_globals, frame.f_locals)

    interpreter = ConsoleWriter()

    try:
        code = compile_command(expression)
    except (OverflowError, SyntaxError, ValueError):
        # Case 1
        interpreter.showsyntaxerror()
        return False

    if code is None:
        # Case 2
        return True

    #Case 3

    try:
        Exec(code, updated_globals, frame.f_locals)

    except SystemExit:
        raise
    except:
        interpreter.showtraceback()

    return False

#=======================================================================================================================
# main
#=======================================================================================================================