Python sys.ps2() Examples

The following are 30 code examples of sys.ps2(). 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 sys , or try the search function .
Example #1
Source File: CLI.py    From pycopia with Apache License 2.0 7 votes vote down vote up
def python(self, argv):
        import code
        ns = self._get_ns()
        console = code.InteractiveConsole(ns)
        console.raw_input = self._ui.user_input
        try:
            saveps1, saveps2 = sys.ps1, sys.ps2
        except AttributeError:
            saveps1, saveps2 = ">>> ", "... "
        sys.ps1, sys.ps2 = "%%GPython%%N:%s> " % (self._obj.__class__.__name__,), "more> "
        if readline:
            oc = readline.get_completer()
            readline.set_completer(Completer(ns).complete)
        console.interact("You are now in Python. ^D exits.")
        if readline:
            readline.set_completer(oc)
        sys.ps1, sys.ps2 = saveps1, saveps2
        self._reset_scopes()


# This is needed to reset PagedIO so background events don't cause the pager to activate. 
Example #2
Source File: __main__.py    From panasonic-viera with MIT License 7 votes vote down vote up
def interact(self, locals=None):
        class LambdaConsole(code.InteractiveConsole):
            def runsource(code_console, source, filename=None, symbol=None):
                try:
                    self.runner.run(source)
                except SystemExit:
                    raise
                except:
                    code_console.showtraceback()
                return False

        try:
            import readline; readline
        except ImportError:
            pass

        ps1, ps2 = getattr(sys, 'ps1', None), getattr(sys, 'ps2', None)
        try:
            sys.ps1, sys.ps2 = self.ps1, self.ps2
            LambdaConsole(locals=locals, filename="<demo>").interact(banner='')
        finally:
            sys.ps1, sys.ps2 = ps1, ps2 
Example #3
Source File: interact.py    From ironpython2 with Apache License 2.0 7 votes vote down vote up
def OnEditCopyCode(self, command, code):
		""" Sanitizes code from interactive window, removing prompts and output,
			and inserts it in the clipboard."""
		code=self.GetSelText()
		lines=code.splitlines()
		out_lines=[]
		for line in lines:
			if line.startswith(sys.ps1):
				line=line[len(sys.ps1):]
				out_lines.append(line)
			elif line.startswith(sys.ps2):
				line=line[len(sys.ps2):]
				out_lines.append(line)
		out_code=os.linesep.join(out_lines)
		win32clipboard.OpenClipboard()
		try:
			win32clipboard.SetClipboardData(win32clipboard.CF_UNICODETEXT, unicode(out_code))
		finally:
			win32clipboard.CloseClipboard() 
Example #4
Source File: test_superconsole.py    From ironpython3 with Apache License 2.0 6 votes vote down vote up
def test_cp4299(self):
        superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')
        superConsole.SendKeys('import sys{ENTER}')
        superConsole.SendKeys('print sys.ps1{ENTER}')
        superConsole.SendKeys('print sys.ps2{ENTER}')
        
        superConsole.SendKeys('sys.ps1 = "abc "{ENTER}')
        superConsole.SendKeys('sys.ps2 = "xyz "{ENTER}')
        superConsole.SendKeys('def f{(}{)}:{ENTER}    pass{ENTER}{ENTER}')
        superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')
        lines = getTestOutput()[0]
        expected_lines = ['>>> import sys\n', 
                        '>>> print sys.ps1\n', '>>> \n', 
                        '>>> print sys.ps2\n', '... \n', 
                        '>>> sys.ps1 = "abc "\n', 'abc sys.ps2 = "xyz "\n', 
                        'abc def f():\n', 'xyz         pass\n', 'xyz         \n', 
                        'abc outputRedirectStop()\n']
        
        for i in xrange(len(lines)):
            AreEqual(lines[i], expected_lines[i])
        AreEqual(len(lines), len(expected_lines)) 
Example #5
Source File: replwrap.py    From pipenv-sublime with MIT License 6 votes vote down vote up
def bash(command="bash"):
    """Start a bash shell and return a :class:`REPLWrapper` object."""
    bashrc = os.path.join(os.path.dirname(__file__), 'bashrc.sh')
    child = pexpect.spawn(command, ['--rcfile', bashrc], echo=False,
                          encoding='utf-8')

    # If the user runs 'env', the value of PS1 will be in the output. To avoid
    # replwrap seeing that as the next prompt, we'll embed the marker characters
    # for invisible characters in the prompt; these show up when inspecting the
    # environment variable, but not when bash displays the prompt.
    ps1 = PEXPECT_PROMPT[:5] + u'\\[\\]' + PEXPECT_PROMPT[5:]
    ps2 = PEXPECT_CONTINUATION_PROMPT[:5] + u'\\[\\]' + PEXPECT_CONTINUATION_PROMPT[5:]
    prompt_change = u"PS1='{0}' PS2='{1}' PROMPT_COMMAND=''".format(ps1, ps2)

    return REPLWrapper(child, u'\\$', prompt_change,
                       extra_init_cmd="export PAGER=cat") 
Example #6
Source File: interaction.py    From daudin with MIT License 6 votes vote down vote up
def runCommand(self, command, commandNumber=1, nCommands=1):
        pipeline = self.pipeline

        if self._handleSpecial(command):
            return

        try:
            incomplete, doPrint = pipeline.run(command, commandNumber,
                                               nCommands)
        except KeyboardInterrupt:
            print('^C', file=sys.stderr)
            self.reset()
            return False
        except Exception:
            print(traceback.format_exc(), file=sys.stderr)
            self.reset()
            return False
        else:
            self.prompt = sys.ps2 if incomplete else sys.ps1
            if doPrint:
                pipeline.print_()

        return True 
Example #7
Source File: CLI.py    From pycopia with Apache License 2.0 6 votes vote down vote up
def python(self, argv):
        import code
        ns = self._get_ns()
        console = code.InteractiveConsole(ns)
        console.raw_input = self._ui.user_input
        try:
            saveps1, saveps2 = sys.ps1, sys.ps2
        except AttributeError:
            saveps1, saveps2 = ">>> ", "... "
        sys.ps1, sys.ps2 = "%%GPython%%N:%s> " % (self._obj.__class__.__name__,), "more> "
        if readline:
            oc = readline.get_completer()
            readline.set_completer(Completer(ns).complete)
        console.interact("You are now in Python. ^D exits.")
        if readline:
            readline.set_completer(oc)
        sys.ps1, sys.ps2 = saveps1, saveps2
        self._reset_scopes() 
Example #8
Source File: replwrap.py    From pipenv with MIT License 6 votes vote down vote up
def bash(command="bash"):
    """Start a bash shell and return a :class:`REPLWrapper` object."""
    bashrc = os.path.join(os.path.dirname(__file__), 'bashrc.sh')
    child = pexpect.spawn(command, ['--rcfile', bashrc], echo=False,
                          encoding='utf-8')

    # If the user runs 'env', the value of PS1 will be in the output. To avoid
    # replwrap seeing that as the next prompt, we'll embed the marker characters
    # for invisible characters in the prompt; these show up when inspecting the
    # environment variable, but not when bash displays the prompt.
    ps1 = PEXPECT_PROMPT[:5] + u'\\[\\]' + PEXPECT_PROMPT[5:]
    ps2 = PEXPECT_CONTINUATION_PROMPT[:5] + u'\\[\\]' + PEXPECT_CONTINUATION_PROMPT[5:]
    prompt_change = u"PS1='{0}' PS2='{1}' PROMPT_COMMAND=''".format(ps1, ps2)

    return REPLWrapper(child, u'\\$', prompt_change,
                       extra_init_cmd="export PAGER=cat") 
Example #9
Source File: backdoros.py    From backdoros with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _do_PYREPL(self, params):
        # SOURCE: https://github.com/python/cpython/blob/e42b705188271da108de42b55d9344642170aa2b/Lib/code.py
        cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
        self.push("=== PYREPL START ===\nPython %s on %s\n%s\n" % (sys.version, sys.platform, cprt))

        try:
            sys.ps1
        except AttributeError:
            sys.ps1 = ">>> "

        try:
            sys.ps2
        except AttributeError:
            sys.ps2 = "... "

        self.push(sys.ps1)

        # Redirect STDOUT & STDERR
        self._stdout = sys.stdout
        sys.stdout = IOProxy(self, prefix="STDOUT")
        self._stderr = sys.stderr
        sys.stderr = IOProxy(self, prefix="STDERR")

        self._in_repl = True 
Example #10
Source File: test_superconsole.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_cp4299(self):
        superConsole.SendKeys('outputRedirectStart{(}{)}{ENTER}')
        superConsole.SendKeys('import sys{ENTER}')
        superConsole.SendKeys('print sys.ps1{ENTER}')
        superConsole.SendKeys('print sys.ps2{ENTER}')
        
        superConsole.SendKeys('sys.ps1 = "abc "{ENTER}')
        superConsole.SendKeys('sys.ps2 = "xyz "{ENTER}')
        superConsole.SendKeys('def f{(}{)}:{ENTER}    pass{ENTER}{ENTER}')
        superConsole.SendKeys('outputRedirectStop{(}{)}{ENTER}')
        lines = getTestOutput()[0]
        expected_lines = ['>>> import sys\n', 
                        '>>> print sys.ps1\n', '>>> \n', 
                        '>>> print sys.ps2\n', '... \n', 
                        '>>> sys.ps1 = "abc "\n', 'abc sys.ps2 = "xyz "\n', 
                        'abc def f():\n', 'xyz         pass\n', 'xyz         \n', 
                        'abc outputRedirectStop()\n']
        
        for i in xrange(len(lines)):
            AreEqual(lines[i], expected_lines[i])
        AreEqual(len(lines), len(expected_lines)) 
Example #11
Source File: interact.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
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
		# hack for now for event handling.

	# GetBlockBoundary takes a line number, and will return the
	# start and and line numbers of the block, and a flag indicating if the
	# block is a Python code block.
	# If the line specified has a Python prompt, then the lines are parsed
	# backwards and forwards, and the flag is true.
	# If the line does not start with a prompt, the block is searched forward
	# and backward until a prompt _is_ found, and all lines in between without
	# prompts are returned, and the flag is false. 
Example #12
Source File: interact.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def AppendToPrompt(self,bufLines, oldPrompt = None):
		" Take a command and stick it at the end of the buffer (with python prompts inserted if required)."
		self.flush()
		lastLineNo = self.GetLineCount()-1
		line = self.DoGetLine(lastLineNo)
		if oldPrompt and line==oldPrompt:
			self.SetSel(self.GetTextLength()-len(oldPrompt), self.GetTextLength())
			self.ReplaceSel(sys.ps1)
		elif (line!=str(sys.ps1)):
			if len(line)!=0: self.write('\n')
			self.write(sys.ps1)
		self.flush()
		self.idle.text.mark_set("iomark", "end-1c")
		if not bufLines:
			return
		terms = (["\n" + sys.ps2] * (len(bufLines)-1)) + ['']
		for bufLine, term in zip(bufLines, terms):
			if bufLine.strip():
				self.write( bufLine + term )
		self.flush() 
Example #13
Source File: code.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def runsource(self, source, filename="<input>", symbol="single"):
        """Compile and run some source in the interpreter.

        Arguments are as for compile_command().

        One several things can happen:

        1) The input is incorrect; compile_command() raised an
        exception (SyntaxError or OverflowError).  A syntax traceback
        will be printed by calling the showsyntaxerror() method.

        2) The input is incomplete, and more input is required;
        compile_command() returned None.  Nothing happens.

        3) The input is complete; compile_command() returned a code
        object.  The code is executed by calling self.runcode() (which
        also handles run-time exceptions, except for SystemExit).

        The return value is True in case 2, False in the other cases (unless
        an exception is raised).  The return value can be used to
        decide whether to use sys.ps1 or sys.ps2 to prompt the next
        line.

        """
        try:
            code = self.compile(source, filename, symbol)
        except (OverflowError, SyntaxError, ValueError):
            # Case 1
            self.showsyntaxerror(filename)
            return False

        if code is None:
            # Case 2
            return True

        # Case 3
        self.runcode(code)
        return False 
Example #14
Source File: code.py    From CTFCrackTools-V2 with GNU General Public License v3.0 5 votes vote down vote up
def runsource(self, source, filename="<input>", symbol="single"):
        """Compile and run some source in the interpreter.

        Arguments are as for compile_command().

        One several things can happen:

        1) The input is incorrect; compile_command() raised an
        exception (SyntaxError or OverflowError).  A syntax traceback
        will be printed by calling the showsyntaxerror() method.

        2) The input is incomplete, and more input is required;
        compile_command() returned None.  Nothing happens.

        3) The input is complete; compile_command() returned a code
        object.  The code is executed by calling self.runcode() (which
        also handles run-time exceptions, except for SystemExit).

        The return value is True in case 2, False in the other cases (unless
        an exception is raised).  The return value can be used to
        decide whether to use sys.ps1 or sys.ps2 to prompt the next
        line.

        """
        try:
            code = self.compile(source, filename, symbol)
        except (OverflowError, SyntaxError, ValueError):
            # Case 1
            self.showsyntaxerror(filename)
            return False

        if code is None:
            # Case 2
            return True

        # Case 3
        self.runcode(code)
        return False 
Example #15
Source File: code.py    From odoo13-x64 with GNU General Public License v3.0 5 votes vote down vote up
def runsource(self, source, filename="<input>", symbol="single"):
        """Compile and run some source in the interpreter.

        Arguments are as for compile_command().

        One several things can happen:

        1) The input is incorrect; compile_command() raised an
        exception (SyntaxError or OverflowError).  A syntax traceback
        will be printed by calling the showsyntaxerror() method.

        2) The input is incomplete, and more input is required;
        compile_command() returned None.  Nothing happens.

        3) The input is complete; compile_command() returned a code
        object.  The code is executed by calling self.runcode() (which
        also handles run-time exceptions, except for SystemExit).

        The return value is True in case 2, False in the other cases (unless
        an exception is raised).  The return value can be used to
        decide whether to use sys.ps1 or sys.ps2 to prompt the next
        line.

        """
        try:
            code = self.compile(source, filename, symbol)
        except (OverflowError, SyntaxError, ValueError):
            # Case 1
            self.showsyntaxerror(filename)
            return False

        if code is None:
            # Case 2
            return True

        # Case 3
        self.runcode(code)
        return False 
Example #16
Source File: pydevconsole_code_for_ironpython.py    From filmkodi with Apache License 2.0 5 votes vote down vote up
def runsource(self, source, filename="<input>", symbol="single"):
        """Compile and run some source in the interpreter.

        Arguments are as for compile_command().

        One several things can happen:

        1) The input is incorrect; compile_command() raised an
        exception (SyntaxError or OverflowError).  A syntax traceback
        will be printed by calling the showsyntaxerror() method.

        2) The input is incomplete, and more input is required;
        compile_command() returned None.  Nothing happens.

        3) The input is complete; compile_command() returned a code
        object.  The code is executed by calling self.runcode() (which
        also handles run-time exceptions, except for SystemExit).

        The return value is True in case 2, False in the other cases (unless
        an exception is raised).  The return value can be used to
        decide whether to use sys.ps1 or sys.ps2 to prompt the next
        line.

        """
        try:
            code = self.compile(source, filename, symbol)
        except (OverflowError, SyntaxError, ValueError):
            # Case 1
            self.showsyntaxerror(filename)
            return False

        if code is None:
            # Case 2
            return True

        # Case 3
        self.runcode(code)
        return False 
Example #17
Source File: console.py    From aioconsole with GNU General Public License v3.0 5 votes vote down vote up
def _interact(self, banner=None):
        # Get ps1 and ps2
        try:
            sys.ps1
        except AttributeError:
            sys.ps1 = ">>> "
        try:
            sys.ps2
        except AttributeError:
            sys.ps2 = "... "
        # Print banner
        if banner is None:
            banner = self.get_default_banner()
        self.write("%s\n" % str(banner))
        # Run loop
        more = 0
        while 1:
            try:
                if more:
                    prompt = sys.ps2
                else:
                    prompt = sys.ps1
                try:
                    line = await self.raw_input(prompt)
                except EOFError:
                    self.write("\n")
                    await self.flush()
                    break
                else:
                    more = await self.push(line)
            except asyncio.CancelledError:
                self.write("\nKeyboardInterrupt\n")
                await self.flush()
                self.resetbuffer()
                more = 0 
Example #18
Source File: code.py    From RevitBatchProcessor with GNU General Public License v3.0 5 votes vote down vote up
def runsource(self, source, filename="<input>", symbol="single"):
        """Compile and run some source in the interpreter.

        Arguments are as for compile_command().

        One several things can happen:

        1) The input is incorrect; compile_command() raised an
        exception (SyntaxError or OverflowError).  A syntax traceback
        will be printed by calling the showsyntaxerror() method.

        2) The input is incomplete, and more input is required;
        compile_command() returned None.  Nothing happens.

        3) The input is complete; compile_command() returned a code
        object.  The code is executed by calling self.runcode() (which
        also handles run-time exceptions, except for SystemExit).

        The return value is True in case 2, False in the other cases (unless
        an exception is raised).  The return value can be used to
        decide whether to use sys.ps1 or sys.ps2 to prompt the next
        line.

        """
        try:
            code = self.compile(source, filename, symbol)
        except (OverflowError, SyntaxError, ValueError):
            # Case 1
            self.showsyntaxerror(filename)
            return False

        if code is None:
            # Case 2
            return True

        # Case 3
        self.runcode(code)
        return False 
Example #19
Source File: code.py    From Carnets with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def runsource(self, source, filename="<input>", symbol="single"):
        """Compile and run some source in the interpreter.

        Arguments are as for compile_command().

        One several things can happen:

        1) The input is incorrect; compile_command() raised an
        exception (SyntaxError or OverflowError).  A syntax traceback
        will be printed by calling the showsyntaxerror() method.

        2) The input is incomplete, and more input is required;
        compile_command() returned None.  Nothing happens.

        3) The input is complete; compile_command() returned a code
        object.  The code is executed by calling self.runcode() (which
        also handles run-time exceptions, except for SystemExit).

        The return value is True in case 2, False in the other cases (unless
        an exception is raised).  The return value can be used to
        decide whether to use sys.ps1 or sys.ps2 to prompt the next
        line.

        """
        try:
            code = self.compile(source, filename, symbol)
        except (OverflowError, SyntaxError, ValueError):
            # Case 1
            self.showsyntaxerror(filename)
            return False

        if code is None:
            # Case 2
            return True

        # Case 3
        self.runcode(code)
        return False 
Example #20
Source File: console.py    From win-unicode-console with MIT License 5 votes vote down vote up
def interact(self):
		#sys.ps1 = "~>> "
		#sys.ps2 = "~.. "
		
		try:
			sys.ps1
		except AttributeError:
			sys.ps1 = ">>> "
		
		try:
			sys.ps2
		except AttributeError:
			sys.ps2 = "... "
		
		more = 0
		while not self.done:
			try:
				if more:
					try:
						prompt = sys.ps2
					except AttributeError:
						prompt = ""
				else:
					try:
						prompt = sys.ps1
					except AttributeError:
						prompt = ""
				
				try:
					line = self.raw_input(prompt)
				except EOFError:
					self.on_EOF()
				else:
					more = self.push(line)
				
			except KeyboardInterrupt:
				self.write("\nKeyboardInterrupt\n")
				self.resetbuffer()
				more = 0 
Example #21
Source File: code.py    From Project-New-Reign---Nemesis-Main with GNU General Public License v3.0 5 votes vote down vote up
def runsource(self, source, filename="<input>", symbol="single"):
        """Compile and run some source in the interpreter.

        Arguments are as for compile_command().

        One several things can happen:

        1) The input is incorrect; compile_command() raised an
        exception (SyntaxError or OverflowError).  A syntax traceback
        will be printed by calling the showsyntaxerror() method.

        2) The input is incomplete, and more input is required;
        compile_command() returned None.  Nothing happens.

        3) The input is complete; compile_command() returned a code
        object.  The code is executed by calling self.runcode() (which
        also handles run-time exceptions, except for SystemExit).

        The return value is True in case 2, False in the other cases (unless
        an exception is raised).  The return value can be used to
        decide whether to use sys.ps1 or sys.ps2 to prompt the next
        line.

        """
        try:
            code = self.compile(source, filename, symbol)
        except (OverflowError, SyntaxError, ValueError):
            # Case 1
            self.showsyntaxerror(filename)
            return False

        if code is None:
            # Case 2
            return True

        # Case 3
        self.runcode(code)
        return False 
Example #22
Source File: code.py    From ironpython3 with Apache License 2.0 5 votes vote down vote up
def runsource(self, source, filename="<input>", symbol="single"):
        """Compile and run some source in the interpreter.

        Arguments are as for compile_command().

        One several things can happen:

        1) The input is incorrect; compile_command() raised an
        exception (SyntaxError or OverflowError).  A syntax traceback
        will be printed by calling the showsyntaxerror() method.

        2) The input is incomplete, and more input is required;
        compile_command() returned None.  Nothing happens.

        3) The input is complete; compile_command() returned a code
        object.  The code is executed by calling self.runcode() (which
        also handles run-time exceptions, except for SystemExit).

        The return value is True in case 2, False in the other cases (unless
        an exception is raised).  The return value can be used to
        decide whether to use sys.ps1 or sys.ps2 to prompt the next
        line.

        """
        try:
            code = self.compile(source, filename, symbol)
        except (OverflowError, SyntaxError, ValueError):
            # Case 1
            self.showsyntaxerror(filename)
            return False

        if code is None:
            # Case 2
            return True

        # Case 3
        self.runcode(code)
        return False 
Example #23
Source File: replwrap.py    From pipenv-sublime with MIT License 5 votes vote down vote up
def python(command="python"):
    """Start a Python shell and return a :class:`REPLWrapper` object."""
    return REPLWrapper(command, u">>> ", u"import sys; sys.ps1={0!r}; sys.ps2={1!r}") 
Example #24
Source File: replwrap.py    From camr with GNU General Public License v2.0 5 votes vote down vote up
def python(command="python"):
    """Start a Python shell and return a :class:`REPLWrapper` object."""
    return REPLWrapper(command, u(">>> "), u("import sys; sys.ps1={0!r}; sys.ps2={1!r}")) 
Example #25
Source File: code.py    From Imogen with MIT License 5 votes vote down vote up
def runsource(self, source, filename="<input>", symbol="single"):
        """Compile and run some source in the interpreter.

        Arguments are as for compile_command().

        One several things can happen:

        1) The input is incorrect; compile_command() raised an
        exception (SyntaxError or OverflowError).  A syntax traceback
        will be printed by calling the showsyntaxerror() method.

        2) The input is incomplete, and more input is required;
        compile_command() returned None.  Nothing happens.

        3) The input is complete; compile_command() returned a code
        object.  The code is executed by calling self.runcode() (which
        also handles run-time exceptions, except for SystemExit).

        The return value is True in case 2, False in the other cases (unless
        an exception is raised).  The return value can be used to
        decide whether to use sys.ps1 or sys.ps2 to prompt the next
        line.

        """
        try:
            code = self.compile(source, filename, symbol)
        except (OverflowError, SyntaxError, ValueError):
            # Case 1
            self.showsyntaxerror(filename)
            return False

        if code is None:
            # Case 2
            return True

        # Case 3
        self.runcode(code)
        return False 
Example #26
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def execution_loop(self):
        """loop on the main thread which is responsible for executing code"""
        
        if sys.platform == 'cli' and sys.version_info[:3] < (2, 7, 1):
            # IronPython doesn't support thread.interrupt_main until 2.7.1
            import System
            self.main_thread = System.Threading.Thread.CurrentThread

        # save our selves so global lookups continue to work (required pre-2.6)...
        cur_modules = set()
        try:
            cur_ps1 = sys.ps1
            cur_ps2 = sys.ps2
        except:
            # CPython/IronPython don't set sys.ps1 for non-interactive sessions, Jython and PyPy do
            sys.ps1 = cur_ps1 = '>>> '
            sys.ps2 = cur_ps2 = '... '

        self.send_prompt(cur_ps1, cur_ps2)

        # launch the startup script if one has been specified
        if self.launch_file:
            try:
                self.run_file_as_main(self.launch_file, '')
            except:
                print('error in launching startup script:')
                traceback.print_exc()

        while True:
            exit, cur_modules, cur_ps1, cur_ps2 = self.run_one_command(cur_modules, cur_ps1, cur_ps2)
            if exit:
                return 
Example #27
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_prompt(self, ps1, ps2, update_all = True):
        """sends the current prompt to the interactive window"""
        with self.send_lock:
            write_bytes(self.conn, ReplBackend._PRPC)
            write_string(self.conn, ps1)
            write_string(self.conn, ps2)
            write_int(self.conn, update_all) 
Example #28
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_prompt(self, ps1, ps2, update_all = True):
        """sends the current prompt to the interactive window"""
        with self.send_lock:
            write_bytes(self.conn, ReplBackend._PRPC)
            write_string(self.conn, ps1)
            write_string(self.conn, ps2)
            write_int(self.conn, update_all) 
Example #29
Source File: consolewidget.py    From qutebrowser with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent=None):
        super().__init__(parent)
        if not hasattr(sys, 'ps1'):
            sys.ps1 = '>>> '
        if not hasattr(sys, 'ps2'):
            sys.ps2 = '... '
        namespace = {
            '__name__': '__console__',
            '__doc__': None,
            'q_app': QApplication.instance(),
            # We use parent as self here because the user "feels" the whole
            # console, not just the line edit.
            'self': parent,
            'objreg': objreg,
        }
        self._more = False
        self._buffer = []  # type: typing.MutableSequence[str]
        self._lineedit = ConsoleLineEdit(namespace, self)
        self._lineedit.execute.connect(self.push)
        self._output = ConsoleTextEdit()
        self.write(self._curprompt())
        self._vbox = QVBoxLayout()
        self._vbox.setSpacing(0)
        self._vbox.addWidget(self._output)
        self._vbox.addWidget(self._lineedit)
        stylesheet.set_register(self)
        self.setLayout(self._vbox)
        self._lineedit.setFocus()
        self._interpreter = code.InteractiveInterpreter(namespace) 
Example #30
Source File: visualstudio_py_repl.py    From iot-utilities with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def send_prompt(self, ps1, ps2, update_all = True):
        """sends the current prompt to the interactive window"""
        with self.send_lock:
            write_bytes(self.conn, ReplBackend._PRPC)
            write_string(self.conn, ps1)
            write_string(self.conn, ps2)
            write_int(self.conn, update_all)