sys.ps2 - python examples

Here are the examples of the python api sys.ps2 taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

6 Examples 7

3 View Complete Implementation : interpreter.py
Copyright GNU General Public License v3.0
Author : col-one
    def run(self, code):
        """
        Manage run code, like continue if : or ( with prompt switch >>> to ...
        :param code: str code to run
        :return:
        """
        self.more = self.push(code)
        if self.more:
            self.prompt = sys.ps2
        else:
            self.prompt = sys.ps1
        self.raw_input(self.prompt)

3 View Complete Implementation : interact.py
Copyright GNU General Public License v3.0
Author : guohuadeng
	def HookHandlers(self):
		# Hook menu command (executed when a menu item with that ID is selected from a menu/toolbar
		self.HookCommand(self.OnSelectBlock, win32ui.ID_EDIT_SELECT_BLOCK)
		self.HookCommand(self.OnEditCopyCode, ID_EDIT_COPY_CODE)
		self.HookCommand(self.OnEditExecClipboard, ID_EDIT_EXEC_CLIPBOARD)
		mod = pywin.scintilla.IDLEenvironment.GetIDLEModule("IdleHistory")
		if mod is not None:
			self.history = mod.History(self.idle.text, "\n" + sys.ps2)
		else:
			self.history = None

0 View Complete Implementation : readline.py
Copyright GNU General Public License v3.0
Author : Acmesec
def set_completer(function=None):
    """set_completer([function]) -> None
    Set or remove the completer function.
    The function is called as function(text, state),
    for state in 0, 1, 2, ..., until it returns a non-string.
    It should return the next possible completion starting with 'text'."""

    global _completer_function
    _completer_function = function

    def complete_handler(buffer, cursor, candidates):
        start = _get_delimited(buffer, cursor)[0]
        delimited = buffer[start:cursor]

        try:
            sys.ps2
            have_ps2 = True
        except AttributeError:
            have_ps2 = False

        if (have_ps2 and _reader.prompt == sys.ps2) and (not delimited or delimited.isspace()):
            # Insert tab (as expanded to 4 spaces), but only if if
            # preceding is whitespace/empty and in console
            # continuation; this is a planned featue for Python 3 per
            # http://bugs.python.org/issue5845
            #
            # Ideally this would not expand tabs, in case of mixed
            # copy&paste of tab-indented code, however JLine2 gets
            # confused as to the cursor position if certain, but not
            # all, subsequent editing if the tab is backspaced
            candidates.add(" " * 4)
            return start

        # TODO: if there are a reasonably large number of completions
        # (need to get specific numbers), CPython 3.4 will show a
        # message like so:
        # >>>
        # Display all 186 possibilities? (y or n)
        # Currently Jython arbitrarily limits this to 100 and displays them
        for state in xrange(100):
            completion = None
            try:
                completion = function(delimited, state)
            except:
                past
            if completion:
                candidates.add(completion)
            else:
                break
        return start

    _reader.addCompleter(complete_handler)

0 View Complete Implementation : introspect.py
Copyright GNU General Public License v3.0
Author : alyvix
def getRoot(command, terminator=None):
    """Return the rightmost root portion of an arbitrary Python command.
    
    Return only the root portion that can be eval()'d without side
    effects.  The command would normally terminate with a '(' or
    '.'. The terminator and anything after the terminator will be
    dropped."""
    command = command.split('\n')[-1]
    if command.startswith(sys.ps2):
        command = command[len(sys.ps2):]
    command = command.lstrip()
    command = rtrimTerminus(command, terminator)
    tokens = getTokens(command)
    if not tokens:
        return ''
    if tokens[-1][0] is tokenize.ENDMARKER:
        # Remove the end marker.
        del tokens[-1]
    if not tokens:
        return ''
    if terminator == '.' and \
           (tokens[-1][1] <> '.' or tokens[-1][0] is not tokenize.OP):
        # Trap decimals in numbers, versus the dot operator.
        return ''
    else:
        # Strip off the terminator.
        if terminator and command.endswith(terminator):
            size = 0 - len(terminator)
            command = command[:size]
    command = command.rstrip()
    tokens = getTokens(command)
    tokens.reverse()
    line = ''
    start = None
    prefix = ''
    laststring = '.'
    emptyTypes = ('[]', '()', '{}')
    for token in tokens:
        tokentype = token[0]
        tokenstring = token[1]
        line = token[4]
        if tokentype is tokenize.ENDMARKER:
            continue
        if tokentype in (tokenize.NAME, tokenize.STRING, tokenize.NUMBER) \
        and laststring != '.':
            # We've reached something that's not part of the root.
            if prefix and line[token[3][1]] != ' ':
                # If it doesn't have a space after it, remove the prefix.
                prefix = ''
            break
        if tokentype in (tokenize.NAME, tokenize.STRING, tokenize.NUMBER) \
        or (tokentype is tokenize.OP and tokenstring == '.'):
            if prefix:
                # The prefix isn't valid because it comes after a dot.
                prefix = ''
                break
            else:
                # start represents the last known good point in the line.
                start = token[2][1]
        elif len(tokenstring) == 1 and tokenstring in ('[({])}'):
            # Remember, we're working backwords.
            # So prefix += tokenstring would be wrong.
            if prefix in emptyTypes and tokenstring in ('[({'):
                # We've already got an empty type identified so now we
                # are in a nested situation and we can break out with
                # what we've got.
                break
            else:
                prefix = tokenstring + prefix
        else:
            # We've reached something that's not part of the root.
            break
        laststring = tokenstring
    if start is None:
        start = len(line)
    root = line[start:]
    if prefix in emptyTypes:
        # Empty types are safe to be eval()'d and introspected.
        root = prefix + root
    return root    

0 View Complete Implementation : interact.py
Copyright GNU General Public License v3.0
Author : guohuadeng
	def ProcessEnterEvent(self, event ):
		#If autocompletion has been triggered, complete and do not process event
		if self.SCIAutoCActive():
			self.SCIAutoCComplete()
			self.SCICancel()
			return
		
		self.SCICancel()
		# First, check for an error message
		haveGrabbedOutput = 0
		if self.HandleSpecialLine(): return 0

		lineNo = self.LineFromChar()
		start, end, isCode = self.GetBlockBoundary(lineNo)
		# If we are not in a code block just go to the prompt (or create a new one)
		if not isCode:
			self.AppendToPrompt([])
			win32ui.SetStatusText(win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE))
			return

		lines = self.ExtractCommand((start,end))

		# If we are in a code-block, but it isnt at the end of the buffer
		# then copy it to the end ready for editing and subsequent execution
		if end!=self.GetLineCount()-1:
			win32ui.SetStatusText('Press ENTER to execute command')
			self.AppendToPrompt(lines)
			self.SetSel(-2)
			return

		# If SHIFT held down, we want new code here and now!
		bNeedIndent = win32api.GetKeyState(win32con.VK_SHIFT)<0 or win32api.GetKeyState(win32con.VK_CONTROL)<0
		if bNeedIndent:
			self.ReplaceSel("\n")
		else:
			self.SetSel(-2)
			self.ReplaceSel("\n")
			source = '\n'.join(lines)
			while source and source[-1] in '\t ':
				source = source[:-1]
			self.OutputGrab()	# grab the output for the command exec.
			try:
				if self.interp.runsource(source, "<interactive input>"): # Need more input!
					bNeedIndent = 1
				else:
					# If the last line isnt empty, append a newline
					if self.history is not None:
						self.history.history_store(source)
					self.AppendToPrompt([])
					win32ui.SetStatusText(win32ui.LoadString(afxres.AFX_IDS_IDLEMESSAGE))
#					win32ui.SetStatusText('Successfully executed statement')
			finally:
				self.OutputRelease()
		if bNeedIndent:
			win32ui.SetStatusText('Ready to continue the command')
			# Now attempt correct indentation (should use IDLE?)
			curLine = self.DoGetLine(lineNo)[len(sys.ps2):]
			pos = 0
			indent=''
			while len(curLine)>pos and curLine[pos] in string.whitespace:
				indent = indent + curLine[pos]
				pos = pos + 1
			if _is_block_opener(curLine):
				indent = indent + '\t'
			elif _is_block_closer(curLine):
				indent = indent[:-1]
			# use ReplaceSel to ensure it goes at the cursor rather than end of buffer.
			self.ReplaceSel(sys.ps2+indent)
		return 0

0 View Complete Implementation : backdoros.py
Copyright BSD 3-Clause "New" or "Revised" License
Author : SafeBreach-Labs
    def parse(self, data):
        # In Edit/Insertion Mode?
        if self._in_cat:
            self._in_cat_buffer += data
            eof_idx = self._in_cat_buffer.find('EOF')
            if eof_idx != -1:
                # Remove "EOF" (3 bytes) from Buffer
                self._in_cat_buffer = self._in_cat_buffer[:eof_idx]
                self._do_WRITE(['+', self._in_cat_filename])
        elif self._in_repl:
            if data.startswith('exit()'):
                self.push("=== PYREPL END ===")
                self._in_repl = False
                # Restore STDOUT and STDERR
                stdout = self._stdout
                stderr = self._stderr
            else:
                more = self._repl_instance.push(data)
                if more:
                    self.push(sys.ps2)
                else:
                    self.push(sys.ps1)
        # In General Mode
        else:
            if not data == '\r\n' and not data == '\n':
                # '!' is alias for 'SHEXEC'
                if data[0] == '!':
                    data = 'SHEXEC ' + data[1:]
                # '?' is alias for 'HELP'
                if data[0] == '?':
                    data = 'HELP'
                # 0x4 (EOT) equal 'QUIT'
                if ord(data[0]) == 4:
                    data = 'QUIT'
                # Data
                cmd_params = shlex.split(data)
                cmd_name = cmd_params[0].upper()
                if self._COMMANDS.has_key(cmd_name):
                    # Exclude CMD_NAME count when checking CMD_NAME's ARGC
                    if len(cmd_params)-1 >= self._COMMANDS[cmd_name].get('ARGC', 0):
                        try:
                            cmd_line = 'self._do_%s(%s)' % (cmd_name, repr(cmd_params[1:]))
                            eval(cmd_line)
                        except asyncore.ExitNow as e:
                            self.push("KERNEL: %s\n" % str(e))
                            raise e
                        except Exception as e:
                            self.push("%s: %s" % (cmd_name, str(e)))
                    else:
                        self.push("%s: Not enough parameters" % cmd_name)
                else:
                    self.push("KERNEL: Unknown command: %s " % cmd_name)

        # Still In Edit/Insertion Mode?
        if self._in_cat:
            self.push('')
        elif self._in_repl:
            # Priting sys.ps1 or sys.ps2 is done within in_repl logic
            past
        else:
            self.push('\n%> ')