Here are the examples of the python api sys.ps1 taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.
66 Examples
5
Example 1
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)
3
Example 2
def interact(self, banner=None):
"""Run an interactive session."""
try:
sys.ps1
except AttributeError:
sys.ps1 = '>>>'
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
cprt = ('Type "help", "copyright", "credits" or "license" for '
'more information.')
if banner is None:
self.write("Python %s on %s\n%s\n" %
(sys.version, sys.platform, cprt))
else:
self.write("%s\n" % str(banner))
self.run_commands()
3
Example 3
Project: personfinder Source File: console.py
def connect(url, server_type=None):
remote_api.connect(url, server_type=server_type)
# ConfigureRemoteApi sets os.environ['APPLICATION_ID']
app_id = os.environ['APPLICATION_ID']
sys.ps1 = app_id + '> ' # for the interactive console
3
Example 4
Project: ilastik-0.5 Source File: shellWidget.py
def __useHistory(self):
"""
Private method to display a command from the _history.
"""
if self.histidx < len(self._history):
cmd = self._history[self.histidx]
else:
cmd = QtCore.QString()
self.incrementalSearchString = ""
self.incrementalSearchActive = False
self.setCursorPosition(self.prline, self.prcol + len(self.more and sys.ps1 or sys.ps2))
self.setSelection(self.prline,self.prcol,\
self.prline,self.lineLength(self.prline))
self.removeSelectedText()
self.__insertText(cmd)
3
Example 5
def _display_completions(self, completions):
if not completions:
return
self.console.write('\n')
wmax = max(map(len, completions))
w, h = self.console.size()
cols = max(1, int((w-1) / (wmax+1)))
rows = int(math.ceil(float(len(completions)) / cols))
for row in range(rows):
s = ''
for col in range(cols):
i = col*rows + row
if i < len(completions):
self.console.write(completions[i].ljust(wmax+1))
self.console.write('\n')
if in_ironpython:
self.prompt=sys.ps1
self._print_prompt()
3
Example 6
Project: rad2py Source File: shell.py
def __init__(self, locals, rawin, stdin, stdout, stderr,
ps1='>>> ', ps2='... ',
globals=None,
debugger=None,
):
"""Create an interactive interpreter object."""
wx.py.interpreter.Interpreter.__init__(self, locals=locals, rawin=rawin,
stdin=stdin, stdout=stdout, stderr=stderr)
sys.ps1 = ps1
sys.ps2 = ps2
self.globals = globals or {}
self.debugger = debugger
3
Example 7
Project: ilastik-0.5 Source File: shellWidget.py
def __QScintillaCharLeft(self, allLinesAllowed = False):
"""
Private method to handle the Cursor Left command.
"""
if self.__isCursorOnLastLine() or allLinesAllowed:
line, col = self.getCursorPosition()
if self.text(line).startsWith(sys.ps1):
if col > len(sys.ps1):
self.SendScintilla(QsciScintilla.SCI_CHARLEFT)
elif self.text(line).startsWith(sys.ps2):
if col > len(sys.ps2):
self.SendScintilla(QsciScintilla.SCI_CHARLEFT)
elif col > 0:
self.SendScintilla(QsciScintilla.SCI_CHARLEFT)
3
Example 8
Project: ilastik-0.5 Source File: shellWidget.py
def __QScintillaDeleteBack(self):
"""
Private method to handle the Backspace key.
"""
if self.__isCursorOnLastLine():
line, col = self.getCursorPosition()
ac = self.isListActive()
oldLength = self.text(line).length()
if self.text(line).startsWith(sys.ps1):
if col > len(sys.ps1):
self.SendScintilla(QsciScintilla.SCI_DELETEBACK)
elif self.text(line).startsWith(sys.ps2):
if col > len(sys.ps2):
self.SendScintilla(QsciScintilla.SCI_DELETEBACK)
elif col > 0:
self.SendScintilla(QsciScintilla.SCI_DELETEBACK)
3
Example 9
Project: cyNaoko Source File: repl.py
def __init__(self, port, host='localhost', locals={}):
self.closing = False
sys.ps1 = PROMPT_STRING
self.port = port
self.host = host
self.socket = socket.socket(socket.AF_INET,
socket.SOCK_STREAM)
self.socket.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
self.socket.bind((self.host, self.port))
self.socket.listen(1)
self.console = code.InteractiveConsole(locals)
super(Repl, self).__init__(target=self._replLoop)
# This thread is relatively self contained and no exceptions
# should bubble up to an external thread. Be warned the program
# may not exit if there's a live socket. (it probably will though
# as the below loop has no exception handler)
self.start()
3
Example 10
def interact(self, *args, **kwargs):
sys.ps1 = self.ps1
puts(self.banner)
try:
import readline
except ImportError:
pass
InteractiveConsole.interact(self, *args, **kwargs)
3
Example 11
Project: TrustRouter Source File: interact.py
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')
3
Example 12
def execute(self):
self._script = str(self.text.toPlainText())
self.console.write("\nRunning script:\n")
self.console.push("exec(_script)")
self.console.new_prompt(sys.ps1)
for out in self.outputs:
signal = out[0]
self.send(signal, getattr(self, signal, None))
3
Example 13
def _display_completions(self, completions):
if not completions:
return
self.console.write('\n')
wmax = max(map(len, completions))
w, h = self.console.size()
cols = max(1, int((w - 1) / (wmax + 1)))
rows = int(math.ceil(float(len(completions)) / cols))
for row in range(rows):
s = ''
for col in range(cols):
i = col * rows + row
if i < len(completions):
self.console.write(completions[i].ljust(wmax + 1))
self.console.write('\n')
if in_ironpython:
self.prompt = sys.ps1
self._print_prompt()
3
Example 14
Project: TrustRouter Source File: interact.py
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, str(out_code))
finally:
win32clipboard.CloseClipboard()
3
Example 15
Project: scapy Source File: config.py
def _prompt_changer(attr,val):
prompt = conf.prompt
try:
ct = val
if isinstance(ct, themes.AnsiColorTheme) and ct.prompt(""):
## ^A and ^B delimit invisible caracters for readline to count right.
## And we need ct.prompt() to do change something or else ^A and ^B will be
## displayed
prompt = "\001%s\002" % ct.prompt("\002"+prompt+"\001")
else:
prompt = ct.prompt(prompt)
except:
pass
sys.ps1 = prompt
3
Example 16
Project: ilastik-0.5 Source File: shellWidget.py
def __QScintillaTab(self):
"""
Private method to handle the Tab key.
"""
if self.isListActive():
self.SendScintilla(QsciScintilla.SCI_TAB)
elif self.__isCursorOnLastLine():
line, index = self.getCursorPosition()
buf = unicode(self.text(line)).replace(sys.ps1, "").replace(sys.ps2, "")
if self.more and not buf[:index-len(sys.ps2)].strip():
self.SendScintilla(QsciScintilla.SCI_TAB)
3
Example 17
def _prompt_changer(attr,val):
prompt = conf.prompt
try:
ct = val
if isinstance(ct, AnsiColorTheme) and ct.prompt(""):
## ^A and ^B delimit invisible caracters for readline to count right.
## And we need ct.prompt() to do change something or else ^A and ^B will be
## displayed
prompt = "\001%s\002" % ct.prompt("\002"+prompt+"\001")
else:
prompt = ct.prompt(prompt)
except:
pass
sys.ps1 = prompt
3
Example 18
Project: ilastik-0.5 Source File: shellWidget.py
def __QScintillaVCHome(self):
"""
Private method to handle the Home key.
"""
if self.isListActive():
self.SendScintilla(QsciScintilla.SCI_VCHOME)
elif self.__isCursorOnLastLine():
line, col = self.getCursorPosition()
if self.text(line).startsWith(sys.ps1):
col = len(sys.ps1)
elif self.text(line).startsWith(sys.ps2):
col = len(sys.ps2)
else:
col = 0
self.setCursorPosition(line, col)
3
Example 19
Project: konch Source File: konch.py
def start(self):
if self.prompt:
sys.ps1 = self.prompt
if self.output:
warnings.warn('Custom output templates not supported by PythonShell.')
code.interact(self.banner, local=self.context)
return None
3
Example 20
def __get_current_line(self):
""" Return the current line """
line, col = self.__getEndPos()
self.setCursorPosition(line,col)
buf = unicode(self.text(line)).replace(sys.ps1, "").replace(sys.ps2, "")
text = buf.split()[-1][:-1]
return text
2
Example 21
def interact(self, banner=None):
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
cprt = ('Type "help", "copyright", "credits" or "license" '
'for more information.')
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
else:
self.write("%s\n" % str(banner))
more = 0
while 1:
try:
if more:
prompt = sys.ps2
else:
prompt = sys.ps1
self.new_prompt(prompt)
yield
try:
line = self.raw_input(prompt)
except EOFError:
self.write("\n")
break
else:
more = self.push(line)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
2
Example 22
def interact(self, banner=None):
"""Closely emulate the interactive Python console.
The optional banner argument specifies the banner to print
before the first interaction; by default it prints a banner
similar to the one printed by the real Python interpreter,
followed by the current class name in parentheses (so as not
to confuse this with the real interpreter -- since it's so
close!).
"""
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
elif banner:
self.write("%s\n" % str(banner))
more = 0
while 1:
try:
if more:
prompt = sys.ps2
else:
prompt = sys.ps1
try:
line = self.raw_input(prompt)
except EOFError:
self.write("\n")
break
else:
more = self.push(line)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
2
Example 23
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
2
Example 24
def interact(self, banner=None):
"""Closely emulate the interactive Python console.
The optional banner argument specify the banner to print
before the first interaction; by default it prints a banner
similar to the one printed by the real Python interpreter,
followed by the current class name in parentheses (so as not
to confuse this with the real interpreter -- since it's so
close!).
"""
try:
sys.ps1 #@UndefinedVariable
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2 #@UndefinedVariable
except AttributeError:
sys.ps2 = "... "
cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
else:
self.write("%s\n" % str(banner))
more = 0
while 1:
try:
if more:
prompt = sys.ps2 #@UndefinedVariable
else:
prompt = sys.ps1 #@UndefinedVariable
try:
line = self.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:
self.write("\n")
break
else:
more = self.push(line)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
2
Example 25
Project: swirlypy Source File: Recording.py
def interact(self, banner=None):
"""Interacts with the user. Each time a complete command is
entered, it is parsed using AST and yielded."""
# XXX: This is a hack to override parent precedence. This needs
# to be fixed in a better way.
self.compile = self.compile_ast
# Borrow a block of code from code.InteractiveConsole
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
elif banner:
self.write("%s\n" % str(banner))
more = 0
while 1:
# Reset the value of latest_parsed.
self.latest_parsed = None
# Make a copy of locals
cpylocals = deepcopy(self.locals)
try:
if more:
prompt = sys.ps2
else:
prompt = sys.ps1
try:
# If we're not at an indented prompt (that is, not
# getting "more"), then we need to ignore empty
# lines. However, they are valid for "more"
# contexts.
line = self.raw_input(prompt)
while (not more) and line == '':
line = self.raw_input(prompt)
except EOFError:
self.write("\n")
break
else:
# self. push(line) traps most exceptions internally
# and prints a traceback to the console, thus warning the user
# of an error. The following detects the event by checking
# if self.push(line) changes sys.last_traceback. In the event
# of an exception, a new instance will replace the old.
tb0 = sys.last_traceback if hasattr(sys,"last_traceback") else None
more = self.push(line)
tb1 = sys.last_traceback if hasattr(sys,"last_traceback") else None
# If an exception has occurred, retain a reference to
# the associated traceback for inclusion in `response`.
tback = tb1 if tb0 != tb1 else None
# A DictDiffer object has 4 fields: added, changed, removed, unchanged,
# These are sets containing variable names only. Attaching values:
# A DictDiffer object has 4 fields: added, changed,
# removed, unchanged, These are sets containing
# variable names only. Attaching values:
diffs = DictDiffer(self.locals, cpylocals)
ad = dict()
for k in diffs.added() - {'__builtins__'}:
ad[k] = self.locals[k]
ch = dict()
for k in diffs.changed():
ch[k] = self.locals[k]
rv = dict()
for k in diffs.removed():
rv[k] = cpylocals[k]
# Check to see if a new value has been parsed yet.
# If so, yield various useful things.
if self.latest_parsed != None:
yield { "ast": self.clean_parsed,
"added": ad,
"changed": ch, "removed":rv,
"values": self.locals[
"__swirlypy_recorder__"],
"traceback": tback}
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
2
Example 26
def __init__(self, interpreter, message="", log='', parent=None):
"""Constructor.
@param interpreter : InteractiveInterpreter in which
the code will be executed
@param message : welcome message string
@param 'parent' : specifies the parent widget.
If no parent widget has been specified, it is possible to
exit the interpreter by Ctrl-D.
"""
QsciScintilla.__init__(self, parent)
GraphicalStreamRedirection.__init__(self)
self.interpreter = interpreter
# user interface setup
self.setAutoIndent(True)
self.setAutoCompletionThreshold(2)
self.setAutoCompletionSource(QsciScintilla.AcsDocuement)
# Lexer
self.setLexer(QsciLexerPython(self))
# Search
self.incrementalSearchString = ""
self.incrementalSearchActive = False
self.inRawMode = False
self.echoInput = True
# Initialize _history
self.historyLists = {}
self.maxHistoryEntries = 30
self._history = []
self.histidx = -1
self.reading = 0
# interpreter prompt.
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
#self.completionText = ""
# Excecution Status
self.more = False
# Multi line execution Buffer
self.execlines = []
# interpreter banner
self.write('The shell running Python %s on %s.\n' %
(sys.version, sys.platform))
self.write('Type "copyright", "credits" or "license"'
' for more information on Python.\n')
self.write(message+'\n')
#self.write("help -> Python help system.\n")
self.write(" object? -> Print details about 'object'\n\n")
self.write(sys.ps1)
#self.standardCommands().clearKeys()
self.keymap = {
Qt.Key_Backspace : self.__QScintillaDeleteBack,
Qt.Key_Delete : self.__QScintillaDelete,
Qt.Key_Return : self.__QScintillaNewline,
Qt.Key_Enter : self.__QScintillaNewline,
Qt.Key_Tab : self.__QScintillaTab,
Qt.Key_Left : self.__QScintillaCharLeft,
Qt.Key_Right : self.__QScintillaCharRight,
Qt.Key_Up : self.__QScintillaLineUp,
Qt.Key_Down : self.__QScintillaLineDown,
Qt.Key_Home : self.__QScintillaVCHome,
Qt.Key_End : self.__QScintillaLineEnd,
}
self.connect(self, QtCore.SIGNAL('userListActivated(int, const QString)'),
self.__completionListSelected)
self.setFocus()
self.setFocusPolicy(QtCore.Qt.StrongFocus)
2
Example 27
def interact(self, banner=None):
"""Closely emulate the interactive Python console.
The optional banner argument specifies the banner to print
before the first interaction; by default it prints a banner
similar to the one printed by the real Python interpreter,
followed by the current class name in parentheses (so as not
to confuse this with the real interpreter -- since it's so
close!).
"""
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
else:
self.write("%s\n" % str(banner))
more = 0
while 1:
try:
if more:
prompt = sys.ps2
else:
prompt = sys.ps1
try:
line = self.raw_input(prompt)
except EOFError:
self.write("\n")
break
else:
more = self.push(line)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
2
Example 28
def __init__(self, parent=None, dict={}, **options):
"""Construct from a parent widget, an optional dictionary to use
as the namespace for execution, and any configuration options."""
Frame.__init__(self, parent)
# Continuation state.
self.continuation = 0
self.error = 0
self.intraceback = 0
self.pasted = 0
# The command history.
self.history = []
self.historyindex = None
self.current = ""
# Completion state.
self.compmenus = []
self.compindex = None
self.compfinish = ""
# Redirection.
self.stdout = OutputPipe(lambda data, w=self.write: w(data, "stdout"))
self.stderr = OutputPipe(lambda data, w=self.write: w(data, "stderr"))
# Interpreter state.
if not hasattr(sys, "ps1"): sys.ps1 = ">>> "
if not hasattr(sys, "ps2"): sys.ps2 = "... "
self.prefixes = [sys.ps1, sys.ps2, ">> ", "> "]
self.startup = "Python %s\n" %( sys.version)
self.startup+= "Debugger instantiated as 'imm'\n\n"
self.dict = dict
# The text box.
self.text = Text(self, insertontime=200, insertofftime=150)
self.text.insert("end", self.startup)
self.text.insert("end", sys.ps1)
self.text.bind("<Return>", self.cb_return)
self.text.bind("<Button-1>", self.cb_select)
self.text.bind("<ButtonRelease-1>", self.cb_position)
self.text.bind("<ButtonRelease-2>", self.cb_paste)
self.text.bind("<Home>", self.cb_home)
self.text.bind("<Control-Home>", self.cb_ctrlhome)
self.text.bind("<Up>", self.cb_back)
self.text.bind("<Down>", self.cb_forward)
self.text.bind("<Configure>", self.cb_cleanup)
self.text.bind("<Expose>", self.cb_cleanup)
self.text.bind("<Key>", self.cb_cleanup)
self.text.bind("<Tab>", self.cb_complete)
self.text.bind("<Left>", self.cb_position)
self.text.bind("<space>", self.cb_space)
self.text.bind("<BackSpace>", self.cb_backspace)
self.text.bind("<Control-w>", self.cb_backspace)
self.text.bind("<KeyRelease-BackSpace>", self.cb_nothing)
self.text.bind("<F1>", self.cb_help)
self.text.bind("<Control-slash>", self.cb_help)
self.text.bind("<Alt-h>", self.cb_help)
# The scroll bar.
self.scroll = Scrollbar(self, command=self.text.yview)
self.text.config(yscrollcommand=self.scroll.set)
self.scroll.pack(side=RIGHT, fill=Y)
self.text.pack(fill=BOTH, expand=1)
self.text.focus()
# Configurable options.
self.options = {"stdoutcolour": "#7020c0",
"stderrcolour": "#c03020",
"morecolour": "#a0d0f0",
"badcolour": "#e0b0b0",
"runcolour": "#90d090"}
apply(self.config, (), self.options)
apply(self.config, (), options)
2
Example 29
def interact(self, banner=None):
"""Closely emulate the interactive Python console.
The optional banner argument specify the banner to print
before the first interaction; by default it prints a banner
similar to the one printed by the real Python interpreter,
followed by the current class name in parentheses (so as not
to confuse this with the real interpreter -- since it's so
close!).
"""
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
cprt = 'Type "help", "copyright", "credits" or "license" for more information.' # noqa
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
else:
self.write("%s\n" % str(banner))
more = 0
while True:
try:
if more:
prompt = sys.ps2
else:
prompt = sys.ps1
try:
line = self.raw_input(prompt)
self.handle.flush()
# 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:
self.terminate()
return
except IOError:
self.terminate()
return
else:
more = self.push(line)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
2
Example 30
def interact(self, banner=None):
"""Closely emulate the interactive Python console.
The optional banner argument specify the banner to print
before the first interaction; by default it prints a banner
similar to the one printed by the real Python interpreter,
followed by the current class name in parentheses (so as not
to confuse this with the real interpreter -- since it's so
close!).
"""
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
cprt = 'Type "help", "copyright", "credits" or "license"'\
' for more information.'
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
else:
self.write("%s\n" % str(banner))
more = 0
while not self._exit:
try:
if more:
prompt = sys.ps2
else:
prompt = sys.ps1
try:
line = self.raw_input(prompt)
if line is None:
continue
# Can be None if sys.stdin was redefined
encoding = getattr(sys.stdin, "encoding", None)
if encoding and isinstance(line, bytes):
line = line.decode(encoding)
except EOFError:
self.write("\n")
break
else:
more = self.push(line)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
2
Example 31
Project: TrustRouter Source File: interact.py
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()
2
Example 32
def interact(self, banner=None):
"""Closely emulate the interactive Python console.
The optional banner argument specify the banner to print
before the first interaction; by default it prints a banner
similar to the one printed by the real Python interpreter,
followed by the current class name in parentheses (so as not
to confuse this with the real interpreter -- since it's so
close!).
"""
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
else:
self.write("%s\n" % str(banner))
more = 0
while 1:
try:
if more:
prompt = sys.ps2
else:
prompt = sys.ps1
try:
line = self.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:
self.write("\n")
break
else:
more = self.push(line)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
2
Example 33
def interact(self, banner=None):
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
else:
self.write("%s\n" % str(banner))
more = 0
while 1:
try:
if more:
prompt = sys.ps2
else:
prompt = sys.ps1
self.new_prompt(prompt)
yield
try:
line = self.raw_input(prompt)
except EOFError:
self.write("\n")
break
else:
more = self.push(line)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
2
Example 34
def interact(self, banner=None):
"""Closely emulate the interactive Python console.
The optional banner argument specify the banner to print
before the first interaction; by default it prints a banner
similar to the one printed by the real Python interpreter,
followed by the current class name in parentheses (so as not
to confuse this with the real interpreter -- since it's so
close!).
"""
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
cprt = 'Type "help", "copyright", "credits" or "license" for more information.'
if banner is None:
self.write("Python %s on %s\n%s\n(%s)\n" %
(sys.version, sys.platform, cprt,
self.__class__.__name__))
else:
self.write("%s\n" % str(banner))
more = 0
while 1:
try:
if more:
prompt = sys.ps2
else:
prompt = sys.ps1
try:
line = self.raw_input(prompt)
except EOFError:
self.write("\n")
break
else:
more = self.push(line)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
2
Example 35
@asyncio.coroutine
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 = yield from self.raw_input(prompt)
except EOFError:
self.write("\n")
yield from self.flush()
break
else:
more = yield from self.push(line)
except asyncio.CancelledError:
self.write("\nKeyboardInterrupt\n")
yield from self.flush()
self.resetbuffer()
more = 0
0
Example 36
def __init__(self, interpreter, completer=None):
""""Initiate text buffer
interpreter must implement resetbuffer() and push()
see code.InteractiveConsole
completer must be callable
see rlcomplete.Complete.complete()
"""
try:
sys.ps1
except AttributeError:
sys.ps1 = ">>> "
try:
sys.ps2
except AttributeError:
sys.ps2 = "... "
self.interpreter = interpreter
self.completer = completer
self.input_buffer = ""
self.more = False
self.history = [""]
self.history_index = 0
0
Example 37
Project: imagrium Source File: Console.py
def newInput(self):
self.startUserInput(str(sys.ps1)+'\t')
0
Example 38
def run_commands(self):
"""Automatically type and execute all commands."""
more = 0
prompt = sys.ps1
for command in self.commands:
try:
prompt = sys.ps2 if more else sys.ps1
try:
magictype(command, prompt_template=prompt, speed=self.speed)
except EOFError:
self.write("\n")
break
else:
if command.strip() == 'exit()':
return
more = self.push(command)
except KeyboardInterrupt:
self.write("\nKeyboardInterrupt\n")
self.resetbuffer()
more = 0
sys.exit(1)
echo_prompt(prompt)
wait_for(RETURNS)
0
Example 39
Project: qutebrowser Source File: consolewidget.py
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,
'qApp': 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 = []
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)
self.setLayout(self._vbox)
self._lineedit.setFocus()
self._interpreter = code.InteractiveInterpreter(namespace)
0
Example 40
Project: python2-trepan Source File: bpy.py
def run(self, args):
try:
from bpython.curtsies import main as main_bpython
except ImportError:
self.errmsg("bpython needs to be installed to run this command")
return
# bpython does it's own history thing.
# Make sure it doesn't damage ours.
have_line_edit = self.debugger.intf[-1].input.line_edit
if have_line_edit:
try:
self.proc.write_history_file()
except IOError:
pass
pass
banner_tmpl='''trepan2 python shell%s
Use dbgr(*string*) to issue debugger command: *string*'''
debug = len(args) > 1 and args[1] == '-d'
if debug:
banner_tmpl += ("\nVariable 'debugger' contains a trepan" +
"debugger object.")
pass
my_locals = {}
# my_globals = None
if self.proc.curframe:
# my_globals = self.proc.curframe.f_globals
if self.proc.curframe.f_locals:
my_locals = self.proc.curframe.f_locals
pass
pass
# Give python and the user a way to get access to the debugger.
if debug: my_locals['debugger'] = self.debugger
my_locals['dbgr'] = self.dbgr
if len(my_locals):
banner=(banner_tmpl % ' with locals')
else:
banner=(banner_tmpl % '')
pass
sys.ps1 = 'trepan2 >>> '
print banner
try:
main_bpython([], my_locals)
except SystemExit:
pass
# restore completion and our history if we can do so.
if hasattr(self.proc.intf[-1], 'complete'):
try:
from readline import set_completer, parse_and_bind
parse_and_bind("tab: complete")
set_completer(self.proc.intf[-1].complete)
except ImportError:
pass
pass
if have_line_edit:
self.proc.read_history_file()
pass
return
0
Example 41
Project: erppeek Source File: test_interact.py
def test_main(self):
env_tuple = ('http://127.0.0.1:8069', 'database', 'usr', None)
mock.patch('sys.argv', new=['erppeek', '--env', 'demo']).start()
read_config = mock.patch('erppeek.read_config',
return_value=env_tuple).start()
getpass = mock.patch('getpass.getpass',
return_value='password').start()
self.service.db.list.return_value = ['database']
self.service.common.login.return_value = 17
self.service.object.execute.side_effect = TypeError
# Launch interactive
self.infunc.side_effect = [
"client\n",
"model\n",
"client.login('gaspard')\n",
"23 + 19\n",
EOFError('Finished')]
erppeek.main()
self.assertEqual(sys.ps1, 'demo >>> ')
self.assertEqual(sys.ps2, 'demo ... ')
expected_calls = self.startup_calls + (
('common.login', 'database', 'usr', 'password'),
('object.execute', 'database', 17, 'password',
'ir.model.access', 'check', 'res.users', 'write'),
('common.login', 'database', 'gaspard', 'password'),
)
self.assertCalls(*expected_calls)
self.assertEqual(getpass.call_count, 2)
self.assertEqual(read_config.call_count, 1)
self.assertEqual(self.interact.call_count, 1)
outlines = self.stdout.popvalue().splitlines()
self.assertSequenceEqual(outlines[-5:], [
"Logged in as 'usr'",
"<Client 'http://127.0.0.1:8069#database'>",
"<bound method Client.model of "
"<Client 'http://127.0.0.1:8069#database'>>",
"Logged in as 'gaspard'",
"42",
])
self.assertOutput(stderr='\x1b[A\n\n')
0
Example 42
Project: djangae Source File: sandbox.py
@contextlib.contextmanager
def _remote(configuration=None, remote_api_stub=None, apiproxy_stub_map=None, **kwargs):
def auth_func():
return raw_input('Google Account Login: '), getpass.getpass('Password: ')
original_apiproxy = apiproxy_stub_map.apiproxy
if configuration.app_id.startswith('dev~'):
app_id = configuration.app_id[4:]
else:
app_id = configuration.app_id
os.environ['HTTP_HOST'] = '{0}.appspot.com'.format(app_id)
os.environ['DEFAULT_VERSION_HOSTNAME'] = os.environ['HTTP_HOST']
try:
from google.appengine.tools.appcfg import APPCFG_CLIENT_ID, APPCFG_CLIENT_NOTSOSECRET
from google.appengine.tools import appengine_rpc_httplib2
params = appengine_rpc_httplib2.HttpRpcServerOAuth2.OAuth2Parameters(
access_token=None,
client_id=APPCFG_CLIENT_ID,
client_secret=APPCFG_CLIENT_NOTSOSECRET,
scope=remote_api_stub._OAUTH_SCOPES,
refresh_token=None,
credential_file=os.path.expanduser("~/.djangae_oauth2_tokens"),
token_uri=None
)
def factory(*args, **kwargs):
kwargs["auth_tries"] = 3
return appengine_rpc_httplib2.HttpRpcServerOAuth2(*args, **kwargs)
remote_api_stub.ConfigureRemoteApi(
app_id=None,
path='/_ah/remote_api',
auth_func=params,
servername='{0}.appspot.com'.format(app_id),
secure=True,
save_cookies=True,
rpc_server_factory=factory
)
except ImportError:
logging.exception("Unable to use oauth2 falling back to username/password")
remote_api_stub.ConfigureRemoteApi(
None,
'/_ah/remote_api',
auth_func,
servername='{0}.appspot.com'.format(app_id),
secure=True,
)
ps1 = getattr(sys, 'ps1', None)
red = "\033[0;31m"
native = "\033[m"
sys.ps1 = red + '(remote) ' + app_id + native + ' >>> '
try:
yield
finally:
apiproxy_stub_map.apiproxy = original_apiproxy
sys.ps1 = ps1
0
Example 43
Project: python2-trepan Source File: python.py
def run(self, args):
# See if python's code module is around
# Python does it's own history thing.
# Make sure it doesn't damage ours.
have_line_edit = self.debugger.intf[-1].input.line_edit
if have_line_edit:
try:
self.proc.write_history_file()
except IOError:
pass
pass
banner_tmpl='''trepan2 python shell%s
Use dbgr(*string*) to issue debugger command: *string*'''
debug = len(args) > 1 and args[1] == '-d'
if debug:
banner_tmpl += ("\nVariable 'debugger' contains a trepan "
"debugger object.")
pass
my_locals = {}
my_globals = None
if self.proc.curframe:
my_globals = self.proc.curframe.f_globals
if self.proc.curframe.f_locals:
my_locals = self.proc.curframe.f_locals
pass
pass
# Give python and the user a way to get access to the debugger.
if debug: my_locals['debugger'] = self.debugger
my_locals['dbgr'] = self.dbgr
# Change from debugger completion to python completion
try:
import readline
except ImportError:
pass
else:
readline.parse_and_bind("tab: complete")
sys.ps1 = 'trepan2 >>> '
if len(my_locals):
interact(banner=(banner_tmpl % ' with locals'),
my_locals=my_locals, my_globals=my_globals)
else:
interact(banner=(banner_tmpl % ''))
pass
# restore completion and our history if we can do so.
if hasattr(self.proc.intf[-1], 'complete'):
try:
from readline import set_completer, parse_and_bind
parse_and_bind("tab: complete")
set_completer(self.proc.intf[-1].complete)
except ImportError:
pass
pass
if have_line_edit:
self.proc.read_history_file()
pass
return
0
Example 44
Project: TrustRouter Source File: interact.py
def GetPromptPrefix(line):
ps1=sys.ps1
if line[:len(ps1)]==ps1: return ps1
ps2=sys.ps2
if line[:len(ps2)]==ps2: return ps2
0
Example 45
Project: python3-trepan Source File: bpy.py
def run(self, args):
try:
from bpython.curtsies import main as main_bpython
except ImportError:
self.errmsg("bpython needs to be installed to run this command")
return
# bpython does it's own history thing.
# Make sure it doesn't damage ours.
have_line_edit = self.debugger.intf[-1].input.line_edit
if have_line_edit:
try:
self.proc.write_history_file()
except IOError:
pass
pass
banner_tmpl='''trepan2 python shell%s
Use dbgr(*string*) to issue debugger command: *string*'''
debug = len(args) > 1 and args[1] == '-d'
if debug:
banner_tmpl += ("\nVariable 'debugger' contains a trepan" +
"debugger object.")
pass
my_locals = {}
# my_globals = None
if self.proc.curframe:
# my_globals = self.proc.curframe.f_globals
if self.proc.curframe.f_locals:
my_locals = self.proc.curframe.f_locals
pass
pass
# Give python and the user a way to get access to the debugger.
if debug: my_locals['debugger'] = self.debugger
my_locals['dbgr'] = self.dbgr
if len(my_locals):
banner=(banner_tmpl % ' with locals')
else:
banner=(banner_tmpl % '')
pass
sys.ps1 = 'trepan2 >>> '
print(banner)
try:
main_bpython([], my_locals)
except SystemExit:
pass
# restore completion and our history if we can do so.
if hasattr(self.proc.intf[-1], 'complete'):
try:
from readline import set_completer, parse_and_bind
parse_and_bind("tab: complete")
set_completer(self.proc.intf[-1].complete)
except ImportError:
pass
pass
if have_line_edit:
self.proc.read_history_file()
pass
return
0
Example 46
Project: TrustRouter Source File: interact.py
def ColorizeInteractiveCode(self, cdoc, styleStart, stylePyStart):
lengthDoc = len(cdoc)
if lengthDoc == 0: return
state = styleStart
# As per comments in Colorize(), we work with the raw utf8
# bytes. To avoid too muych py3k pain, we treat each utf8 byte
# as a latin-1 unicode character - we only use it to compare
# against ascii chars anyway...
chNext = cdoc[0:1].decode('latin-1')
startSeg = 0
i = 0
lastState=state # debug only
while i < lengthDoc:
ch = chNext
chNext = cdoc[i+1:i+2].decode('latin-1')
# trace("ch=%r, i=%d, next=%r, state=%s" % (ch, i, chNext, state))
if state == STYLE_INTERACTIVE_EOL:
if ch not in '\r\n':
self.ColorSeg(startSeg, i-1, state)
startSeg = i
if ch in [sys.ps1[0], sys.ps2[0]]:
state = STYLE_INTERACTIVE_PROMPT
elif cdoc[i:i+len(tracebackHeader)]==tracebackHeader:
state = STYLE_INTERACTIVE_ERROR
else:
state = STYLE_INTERACTIVE_OUTPUT
elif state == STYLE_INTERACTIVE_PROMPT:
if ch not in sys.ps1 + sys.ps2 + " ":
self.ColorSeg(startSeg, i-1, state)
startSeg = i
if ch in '\r\n':
state = STYLE_INTERACTIVE_EOL
else:
state = stylePyStart # Start coloring Python code.
elif state in [STYLE_INTERACTIVE_OUTPUT]:
if ch in '\r\n':
self.ColorSeg(startSeg, i-1, state)
startSeg = i
state = STYLE_INTERACTIVE_EOL
elif state == STYLE_INTERACTIVE_ERROR:
if ch in '\r\n' and chNext and chNext not in string.whitespace:
# Everything including me
self.ColorSeg(startSeg, i, state)
startSeg = i+1
state = STYLE_INTERACTIVE_ERROR_FINALLINE
elif i == 0 and ch not in string.whitespace:
# If we are coloring from the start of a line,
# we need this better check for the last line
# Color up to not including me
self.ColorSeg(startSeg, i-1, state)
startSeg = i
state = STYLE_INTERACTIVE_ERROR_FINALLINE
elif state == STYLE_INTERACTIVE_ERROR_FINALLINE:
if ch in '\r\n':
self.ColorSeg(startSeg, i-1, state)
startSeg = i
state = STYLE_INTERACTIVE_EOL
elif state == STYLE_INTERACTIVE_BANNER:
if ch in '\r\n' and (chNext=='' or chNext in ">["):
# Everything including me
self.ColorSeg(startSeg, i-1, state)
startSeg = i
state = STYLE_INTERACTIVE_EOL
else:
# It is a PythonColorizer state - seek past the end of the line
# and ask the Python colorizer to color that.
end = startSeg
while end < lengthDoc and cdoc[end] not in '\r\n'.encode('ascii'):
end = end + 1
self.ColorizePythonCode( cdoc[:end], startSeg, state)
stylePyStart = self.GetStringStyle(end-1)
if stylePyStart is None:
stylePyStart = pywin.scintilla.formatter.STYLE_DEFAULT
else:
stylePyStart = stylePyStart.name
startSeg =end
i = end - 1 # ready for increment.
chNext = cdoc[end:end+1].decode('latin-1')
state = STYLE_INTERACTIVE_EOL
if lastState != state:
lastState = state
i = i + 1
# and the rest
if startSeg<i:
self.ColorSeg(startSeg, i-1, state)
0
Example 47
Project: python3-trepan Source File: python.py
def run(self, args):
# See if python's code module is around
# Python does it's own history thing.
# Make sure it doesn't damage ours.
have_line_edit = self.debugger.intf[-1].input.line_edit
if have_line_edit:
try:
self.proc.write_history_file()
except IOError:
pass
pass
banner_tmpl='''trepan3 python shell%s
Use dbgr(*string*) to issue debugger command: *string*'''
debug = len(args) > 1 and args[1] == '-d'
if debug:
banner_tmpl += ("\nVariable 'debugger' contains a trepan" +
"debugger object.")
pass
my_locals = {}
my_globals = None
if self.proc.curframe:
my_globals = self.proc.curframe.f_globals
if self.proc.curframe.f_locals:
my_locals = self.proc.curframe.f_locals
pass
pass
# Give python and the user a way to get access to the debugger.
if debug: my_locals['debugger'] = self.debugger
my_locals['dbgr'] = self.dbgr
# Change from debugger completion to python completion
try:
import rlcompleter, readline
except ImportError:
pass
else:
readline.parse_and_bind("tab: complete")
sys.ps1 = 'trepan3k >>> '
if len(my_locals):
interact(banner=(banner_tmpl % ' with locals'),
my_locals=my_locals, my_globals=my_globals)
else:
interact(banner=(banner_tmpl % ''))
pass
# restore completion and our history if we can do so.
if hasattr(self.proc.intf[-1], 'complete'):
try:
from readline import set_completer, parse_and_bind
parse_and_bind("tab: complete")
set_completer(self.proc.intf[-1].complete)
except ImportError:
pass
pass
if have_line_edit:
self.proc.read_history_file()
pass
return
0
Example 48
Project: TrustRouter Source File: interact.py
def GetBlockBoundary( self, lineNo ):
line = self.DoGetLine(lineNo)
maxLineNo = self.GetLineCount()-1
prefix = GetPromptPrefix(line)
if prefix is None: # Non code block
flag = 0
startLineNo = lineNo
while startLineNo>0:
if GetPromptPrefix(self.DoGetLine(startLineNo-1)) is not None:
break # there _is_ a prompt
startLineNo = startLineNo-1
endLineNo = lineNo
while endLineNo<maxLineNo:
if GetPromptPrefix(self.DoGetLine(endLineNo+1)) is not None:
break # there _is_ a prompt
endLineNo = endLineNo+1
else: # Code block
flag = 1
startLineNo = lineNo
while startLineNo>0 and prefix!=str(sys.ps1):
prefix = GetPromptPrefix(self.DoGetLine(startLineNo-1))
if prefix is None:
break; # there is no prompt.
startLineNo = startLineNo - 1
endLineNo = lineNo
while endLineNo<maxLineNo:
prefix = GetPromptPrefix(self.DoGetLine(endLineNo+1))
if prefix is None:
break # there is no prompt
if prefix==str(sys.ps1):
break # this is another command
endLineNo = endLineNo+1
# continue until end of buffer, or no prompt
return (startLineNo, endLineNo, flag)
0
Example 49
def handleLine(self, text):
self.command.append(text)
try:
code = compile_command(string.join(self.command, '\n'))
except SyntaxError:
traceback.print_exc(0)
self.command = []
self.startUserInput(str(sys.ps1)+'\t')
return
if code is None:
self.startUserInput(str(sys.ps2)+'\t')
return
self.command = []
pt = PythonThread(code, self)
self.pythonThread = pt
pt.start()
0
Example 50
Project: TrustRouter Source File: PyParse.py
def find_good_parse_start(self, use_ps1, is_char_in_string=None):
str, pos = self.str, None
if use_ps1:
# shell window
ps1 = '\n' + sys.ps1
i = str.rfind(ps1)
if i >= 0:
pos = i + len(ps1)
# make it look like there's a newline instead
# of ps1 at the start -- hacking here once avoids
# repeated hackery later
self.str = str[:pos-1] + '\n' + str[pos:]
return pos
# File window -- real work.
if not is_char_in_string:
# no clue -- make the caller pass everything
return None
# Peek back from the end for a good place to start,
# but don't try too often; pos will be left None, or
# bumped to a legitimate synch point.
limit = len(str)
for tries in range(5):
i = str.rfind(":\n", 0, limit)
if i < 0:
break
i = str.rfind('\n', 0, i) + 1 # start of colon line
m = _synchre(str, i, limit)
if m and not is_char_in_string(m.start()):
pos = m.start()
break
limit = i
if pos is None:
# Nothing looks like a block-opener, or stuff does
# but is_char_in_string keeps returning true; most likely
# we're in or near a giant string, the colorizer hasn't
# caught up enough to be helpful, or there simply *aren't*
# any interesting stmts. In any of these cases we're
# going to have to parse the whole thing to be sure, so
# give it one last try from the start, but stop wasting
# time here regardless of the outcome.
m = _synchre(str)
if m and not is_char_in_string(m.start()):
pos = m.start()
return pos
# Peeking back worked; look forward until _synchre no longer
# matches.
i = pos + 1
while 1:
m = _synchre(str, i)
if m:
s, i = m.span()
if not is_char_in_string(s):
pos = s
else:
break
return pos