當前位置: 首頁>>代碼示例>>Python>>正文


Python code.compile_command方法代碼示例

本文整理匯總了Python中code.compile_command方法的典型用法代碼示例。如果您正苦於以下問題:Python code.compile_command方法的具體用法?Python code.compile_command怎麽用?Python code.compile_command使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在code的用法示例。


在下文中一共展示了code.compile_command方法的9個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: compile_ast

# 需要導入模塊: import code [as 別名]
# 或者: from code import compile_command [as 別名]
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) 
開發者ID:alexander-bauer,項目名稱:swirlypy,代碼行數:19,代碼來源:Recording.py

示例2: runsource

# 需要導入模塊: import code [as 別名]
# 或者: from code import compile_command [as 別名]
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 
開發者ID:anyant,項目名稱:rssant,代碼行數:16,代碼來源:shell.py

示例3: CMDshell

# 需要導入模塊: import code [as 別名]
# 或者: from code import compile_command [as 別名]
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 
開發者ID:luci,項目名稱:luci-py,代碼行數:28,代碼來源:__main__.py

示例4: key_Return

# 需要導入模塊: import code [as 別名]
# 或者: from code import compile_command [as 別名]
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") 
開發者ID:kuri65536,項目名稱:python-for-android,代碼行數:15,代碼來源:gtk2manhole.py

示例5: _tryExec

# 需要導入模塊: import code [as 別名]
# 或者: from code import compile_command [as 別名]
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 
開發者ID:terrycojones,項目名稱:daudin,代碼行數:57,代碼來源:pipeline.py

示例6: console_exec

# 需要導入模塊: import code [as 別名]
# 或者: from code import compile_command [as 別名]
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
#======================================================================================================================= 
開發者ID:fabioz,項目名稱:PyDev.Debugger,代碼行數:55,代碼來源:pydevconsole.py

示例7: process_input

# 需要導入模塊: import code [as 別名]
# 或者: from code import compile_command [as 別名]
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) 
開發者ID:Vector35,項目名稱:deprecated-binaryninja-python,代碼行數:59,代碼來源:PythonConsole.py

示例8: processKey

# 需要導入模塊: import code [as 別名]
# 或者: from code import compile_command [as 別名]
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() 
開發者ID:kenorb-contrib,項目名稱:BitTorrent,代碼行數:44,代碼來源:pywidgets.py

示例9: console_exec

# 需要導入模塊: import code [as 別名]
# 或者: from code import compile_command [as 別名]
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
#======================================================================================================================= 
開發者ID:mrknow,項目名稱:filmkodi,代碼行數:47,代碼來源:pydevconsole.py


注:本文中的code.compile_command方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。