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
python类ps2()的实例源码
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
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
def GetPromptPrefix(line):
ps1=sys.ps1
if line[:len(ps1)]==ps1: return ps1
ps2=sys.ps2
if line[:len(ps2)]==ps2: return ps2
#############################################################
#
# Colorizer related code.
#
#############################################################
def SetContext(self, globals, locals, name = "Dbg"):
oldPrompt = sys.ps1
if globals is None:
# Reset
sys.ps1 = ">>> "
sys.ps2 = "... "
locals = globals = __main__.__dict__
else:
sys.ps1 = "[%s]>>> " % name
sys.ps2 = "[%s]... " % name
self.interp.locals = locals
self.interp.globals = globals
self.AppendToPrompt([], oldPrompt)
def EnsureNoPrompt(self):
# Get ready to write some text NOT at a Python prompt.
self.flush()
lastLineNo = self.GetLineCount()-1
line = self.DoGetLine(lastLineNo)
if not line or line in [sys.ps1, sys.ps2]:
self.SetSel(self.GetTextLength()-len(line), self.GetTextLength())
self.ReplaceSel('')
else:
# Just add a new line.
self.write('\n')
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
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}"))
def GetPromptPrefix(line):
ps1=sys.ps1
if line[:len(ps1)]==ps1: return ps1
ps2=sys.ps2
if line[:len(ps2)]==ps2: return ps2
#############################################################
#
# Colorizer related code.
#
#############################################################
def SetContext(self, globals, locals, name = "Dbg"):
oldPrompt = sys.ps1
if globals is None:
# Reset
sys.ps1 = ">>> "
sys.ps2 = "... "
locals = globals = __main__.__dict__
else:
sys.ps1 = "[%s]>>> " % name
sys.ps2 = "[%s]... " % name
self.interp.locals = locals
self.interp.globals = globals
self.AppendToPrompt([], oldPrompt)
def EnsureNoPrompt(self):
# Get ready to write some text NOT at a Python prompt.
self.flush()
lastLineNo = self.GetLineCount()-1
line = self.DoGetLine(lastLineNo)
if not line or line in [sys.ps1, sys.ps2]:
self.SetSel(self.GetTextLength()-len(line), self.GetTextLength())
self.ReplaceSel('')
else:
# Just add a new line.
self.write('\n')
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}")
def init_prompts(self):
# Set system prompts, so that scripts can decide if they are running
# interactively.
sys.ps1 = 'In : '
sys.ps2 = '...: '
sys.ps3 = 'Out: '
def interactive_console(mainmodule=None, quiet=False):
# set sys.{ps1,ps2} just before invoking the interactive interpreter. This
# mimics what CPython does in pythonrun.c
if not hasattr(sys, 'ps1'):
sys.ps1 = '>>>> '
if not hasattr(sys, 'ps2'):
sys.ps2 = '.... '
#
if not quiet:
try:
from _pypy_irc_topic import some_topic
text = "%s: ``%s''" % ( irc_header, some_topic())
while len(text) >= 80:
i = text[:80].rfind(' ')
print(text[:i])
text = text[i+1:]
print(text)
except ImportError:
pass
#
try:
if not os.isatty(sys.stdin.fileno()):
# Bail out if stdin is not tty-like, as pyrepl wouldn't be happy
# For example, with:
# subprocess.Popen(['pypy', '-i'], stdin=subprocess.PIPE)
raise ImportError
from pyrepl.simple_interact import check
if not check():
raise ImportError
from pyrepl.simple_interact import run_multiline_interactive_console
except ImportError:
run_simple_interactive_console(mainmodule)
else:
run_multiline_interactive_console(mainmodule)
def run_simple_interactive_console(mainmodule):
import code
if mainmodule is None:
import __main__ as mainmodule
console = code.InteractiveConsole(mainmodule.__dict__, filename='<stdin>')
# some parts of code.py are copied here because it seems to be impossible
# to start an interactive console without printing at least one line
# of banner
more = 0
while 1:
try:
if more:
prompt = getattr(sys, 'ps2', '... ')
else:
prompt = getattr(sys, 'ps1', '>>> ')
try:
line = raw_input(prompt)
# Can be None if sys.stdin was redefined
encoding = getattr(sys.stdin, 'encoding', None)
if encoding and not isinstance(line, unicode):
line = line.decode(encoding)
except EOFError:
console.write("\n")
break
else:
more = console.push(line)
except KeyboardInterrupt:
console.write("\nKeyboardInterrupt\n")
console.resetbuffer()
more = 0
# ____________________________________________________________
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)
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
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}")
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
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