本文整理汇总了Python中readline.add_history函数的典型用法代码示例。如果您正苦于以下问题:Python add_history函数的具体用法?Python add_history怎么用?Python add_history使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了add_history函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: restore_old_history
def restore_old_history(self):
readline.clear_history()
for line in self._oldHistory:
if line is None:
continue
readline.add_history(line)
self._oldHistory = []
开发者ID:eucalyptus-qa,项目名称:shared,代码行数:7,代码来源:epdb.py
示例2: append
def append(self, event):
"""
Append a new history event.
:param str event: event to append
"""
readline.add_history(event)
开发者ID:cfm,项目名称:pypsi,代码行数:7,代码来源:history.py
示例3: run
def run(self):
try:
import readline
except ImportError:
return
hist = builtins.__xonsh_history__
while self.wait_for_gc and hist.gc.is_alive():
time.sleep(0.011) # gc sleeps for 0.01 secs, sleep a beat longer
files = hist.gc.files()
i = 1
for _, _, f in files:
try:
lj = LazyJSON(f, reopen=False)
for command in lj['cmds']:
inp = command['inp'].splitlines()
for line in inp:
if line == 'EOF':
continue
readline.add_history(line)
if RL_LIB is not None:
RL_LIB.history_set_pos(i)
i += 1
lj.close()
except (IOError, OSError, ValueError):
continue
开发者ID:PaulReiber,项目名称:xonsh,代码行数:25,代码来源:readline_shell.py
示例4: set_context
def set_context(self, name):
"""Set the current history context.
This swaps in a new history context by loading
the history from the contexts filename. The
old context's history is saved first.
"""
if name not in self.contexts:
raise ValueError("Invalid history context: %s" % name)
if self.current:
if name == self.current.name:
return
self.save()
self.current = self.contexts[name]
try:
readline.clear_history()
if self.current.obj:
with open(self.current.filename, "r") as f:
lines = pickle.load(f)
for line in lines:
readline.add_history(line)
else:
readline.read_history_file(self.current.filename)
except IOError:
pass
开发者ID:pombredanne,项目名称:steelscript,代码行数:31,代码来源:rest.py
示例5: getInput
def getInput(self):
out = None
if self._default == None:
self._default = datetime.datetime.now(dateutil.tz.tzlocal())
readline.clear_history()
# put the default value into history
readline.add_history(self._formatDate(self._default))
# try to complete during typing.
readline.set_completer_delims('\n;')
readline.parse_and_bind("tab: complete")
readline.set_completer(self.comp)
# get user input until it's acceptable
while out == None:
inp = input(self._display + " [{}]: "
.format(self._formatDate(self._default)))
if inp == "?":
self.printSpec()
else:
try:
out = self.tryParse(inp.strip(), self._default)
except Exception as e:
# although the value is not acceptable, give user
# a chance to modify it.
hist = inp.strip()
if len(hist) > 0:
readline.add_history(inp.strip())
self.printSpec()
readline.clear_history()
readline.set_completer()
# print(">> {}: {}".format(self._display, out.strftime("%Y/%m/%d %H:%M")))
return out
开发者ID:kk1fff,项目名称:caishen,代码行数:35,代码来源:user_input.py
示例6: _run
def _run(self):
"""Go through all commands on a pseudo-shell, and execute them,
caching the passphrase at some point."""
print "Welcome to SFLvault. Type 'help' for help."
prompt = "SFLvault> "
while True:
cmd = raw_input(prompt)
if not cmd:
continue
# Get sys.argv-like parameters
args = shlex.split(cmd)
# Local (shell) cmds take precedence over SFLvaultCommand cmds.
if len(args) and hasattr(self, args[0]):
getattr(self, args[0])()
else:
parser = NoExitParser(usage=optparse.SUPPRESS_USAGE)
runcmd = SFLvaultCommand(self.config, self.vault, parser)
try:
runcmd._run(args)
except ExitParserException, e:
pass
if hasattr(runcmd, 'next_command') \
and platform.system() != 'Windows':
print "[Added to shell history: %s]" % runcmd.next_command
readline.add_history(runcmd.next_command)
开发者ID:cah-rfelsburg,项目名称:sflvault,代码行数:30,代码来源:commands.py
示例7: edit_track
def edit_track(self, files):
input = raw_input('[A]ccept, 1-%d to edit name, s/pattern/repl/g: ' % len(files))
try:
filename = files.keys()[int(input) - 1]
old_name = files[filename]
readline.add_history(old_name)
new_name = raw_input('New name [%s] (press up): ' % old_name)
files[filename] = new_name or old_name
except (ValueError, IndexError):
if input.upper() in ('', 'Y'):
return True
if input.startswith('s/'):
elems = [re.escape(x) for x in input.split('/')]
if len(elems) != 4:
print "W: Malformed regular expression"
return False
count = 0
for filename, name in files.iteritems():
new_name = re.sub(elems[1], elems[2], name)
if name != new_name:
files[filename] = new_name
count += 1
print "I: %d track(s) changed" % count
return False
开发者ID:MechanisM,项目名称:musicdb,代码行数:30,代码来源:commands.py
示例8: input_callback
def input_callback(self, prompt, completions=True):
# Setup subedit
self.curs_set(1)
self.callbacks["set_var"]("input_do_completions", completions)
self.callbacks["set_var"]("input_prompt", prompt)
self.input_box.reset()
self.input_box.refresh()
curses.doupdate()
self.pseudo_input_box.keypad(0)
r = raw_readline()
if not r:
r = ""
self.pseudo_input_box.keypad(1)
# Only add history for commands, not other prompts
if completions:
readline.add_history(r)
self.callbacks["set_var"]("input_prompt", "")
self.input_box.reset()
self.input_box.refresh()
curses.doupdate()
self.curs_set(0)
return r
开发者ID:rahife,项目名称:canto-curses,代码行数:30,代码来源:screen.py
示例9: exec_cmd
def exec_cmd(cmdline):
"""Interpret a command."""
cmd, arg = _parse_cmdline(cmdline)
if not cmd:
print('Bad command.')
else:
cmd_callable = get_cmd(cmd)
if not cmd:
print('Type a command. Try \'help\'.')
elif cmd_callable:
try:
cmd_callable(arg)
except ImproperArgError as e:
print(str(e))
except UsageError as e:
print('usage: ' + cmd + ' ' + str(e))
except MissingDeckError:
print('No active deck. Create a new deck with the \'deck\' '
'command.')
except cards.ScrapeError as e:
print('Scrape failed: ' + str(e))
if 'readline' in sys.modules:
readline.add_history(cmdline)
else:
print('%s is not a command. Try \'help\'.' % str(cmd))
return True
开发者ID:gnarlyskier,项目名称:deckbuilder,代码行数:26,代码来源:deckbuilder.py
示例10: _read_file
def _read_file(self, fname):
"""
Generator to read ScriptLine objects from the file named
`fname`.
"""
lno = 0
# Ignore leading blank lines that would be treated as pauses
inhibit_pause = True
with open(fname, 'r') as f:
for line in f:
# Track the line number
lno += 1
# Parse the line
sc_line = ScriptLine(fname, lno, line)
# Process pauses
if sc_line.type == 'pause':
if inhibit_pause:
# Apply pause inhibition
continue
# Inhibit future pausing
inhibit_pause = True
else:
# Not inhibiting any more pauses
inhibit_pause = False
# Add the line to the history
readline.add_history(sc_line.raw)
# Yield the line
yield sc_line
开发者ID:klmitch,项目名称:demo,代码行数:34,代码来源:script.py
示例11: _add_line_to_history
def _add_line_to_history(self, line):
"""Adds the given line to readline history, only if the line
is non-empty. If the line starts with a prompt symbol, the
prompt is stripped from the line.
"""
if line and HAS_READLINE:
readline.add_history(line)
开发者ID:cody-zhang,项目名称:Ants,代码行数:7,代码来源:doctest_case.py
示例12: multiline
def multiline(self, firstline=''):
full_input = []
# keep a list of the entries that we've made in history
old_hist = []
if firstline:
print ' ' + firstline
full_input.append(firstline)
while True:
if hasReadline:
# add the current readline position
old_hist.append(readline.get_current_history_length())
if self.use_rawinput:
try:
line = raw_input(self.multiline_prompt)
except EOFError:
line = 'EOF'
else:
self.stdout.write(self.multiline_prompt)
self.stdout.flush()
line = self.stdin.readline()
if not len(line):
line = 'EOF'
else:
line = line[:-1] # chop \n
if line == 'EOF':
break
full_input.append(line)
# add the final readline history position
if hasReadline:
old_hist.append(readline.get_current_history_length())
cmd = '\n'.join(full_input) + '\n'
if hasReadline:
# remove the old, individual readline history entries.
# first remove any duplicate entries
old_hist = sorted(set(old_hist))
# Make sure you do this in reversed order so you move from
# the end of the history up.
for pos in reversed(old_hist):
# get_current_history_length returns pos + 1
readline.remove_history_item(pos - 1)
# now add the full line
readline.add_history(cmd)
locals = self.curframe.f_locals
globals = self.curframe.f_globals
print
self.save_history()
try:
try:
code = compile(cmd, '<stdin>', 'single')
exec code in globals, locals
except:
print self._reprExc()
finally:
self.read_history()
开发者ID:eucalyptus-qa,项目名称:shared,代码行数:60,代码来源:epdb.py
示例13: _process_input
def _process_input(self):
if sys.version_info[0] >= 3:
input_impl = input
else:
input_impl = raw_input
while True:
self._idle.wait()
expression = ""
line = ""
while len(expression) == 0 or line.endswith("\\"):
try:
if len(expression) == 0:
line = input_impl(">>> ")
else:
line = input_impl("... ")
except EOFError:
return
if len(line.strip()) > 0:
if len(expression) > 0:
expression += "\n"
expression += line.rstrip("\\")
if HAVE_READLINE:
readline.add_history(expression)
self._idle.clear()
self._reactor.schedule(lambda: self._send_expression(expression))
开发者ID:chubbymaggie,项目名称:frida-python,代码行数:26,代码来源:repl.py
示例14: loop
def loop(self):
"""
Starts the command loop
loop() -> None
"""
# Process commands
# NOTE: doesn't work with ; inside quoted arguments
cmds = [arg.strip() for arg in self._args.command.split(';')] if self._args.command else []
self._entry()
while True:
self._preInput()
try:
if len(cmds):
res = cmds.pop(0)
print(">>> " + res)
readline.add_history(res)
else:
res = input('>>> ').strip()
except EOFError:
print(colored("(EOF)", 'yellow'))
break
self.runCommandRaw(res)
self._postInput()
self._exit()
开发者ID:athleticus,项目名称:marking-console,代码行数:31,代码来源:Console.py
示例15: input
def input(self, prompt=None, *, history=True):
"""Read a single line
Parameters
----------
history: bool, optional
append read line to history (only if ``stdin`` is ``None``) (defaults to ``True``)
Returns
-------
str
the read line
"""
if prompt is None:
prompt = self.__prompt
if self.__stdin is not None:
try:
line = next(self.__stdin)
if readline_module:
readline_module.add_history(line.rstrip('\n'))
return line
except StopIteration:
return None
else:
return input_function(prompt=prompt, history=history) # pylint: disable=bad-builtin
开发者ID:simone-campagna,项目名称:shells-kitchen,代码行数:25,代码来源:interpreter.py
示例16: append
def append(self, event):
'''
Append a new history event.
:param str event: event to append
'''
readline.add_history(event)
开发者ID:Grahack,项目名称:pypsi,代码行数:7,代码来源:history.py
示例17: wrapper
def wrapper(*args, **kwargs):
try:
import readline
handle_readline = True
except ImportError:
handle_readline = False
if handle_readline:
# backup & reset readline completer
old_readline_completer = readline.get_completer()
readline.set_completer((lambda x: x))
# backup & reset readline history
old_readline_history = []
hist_sz = readline.get_current_history_length()
for i in range(1, hist_sz + 1):
line = readline.get_history_item(i)
old_readline_history.append(line)
readline.clear_history()
try:
retval = function(*args, **kwargs)
finally:
if handle_readline:
# restore old readline completer
readline.set_completer(old_readline_completer)
# restore old readline history
readline.clear_history()
for line in old_readline_history:
readline.add_history(line)
return retval
开发者ID:nil0x42,项目名称:phpsploit,代码行数:32,代码来源:isolate_readline_context.py
示例18: add_item
def add_item(self, line, force=False):
# Kludge. pyreadline is a pain in the ass.
from pyreadline import lineobj
from pyreadline.unicode_helper import ensure_unicode
line = ensure_unicode(line.rstrip())
readline.add_history(lineobj.ReadLineTextBuffer(line))
开发者ID:AppScale,项目名称:appscale,代码行数:7,代码来源:history.py
示例19: get_meta
def get_meta(prompt, default, default_list):
default_count = 0
if default_list:
if not default:
count = len(default_list)
if count == 0:
default = ''
else:
if type(default_list[0]) is str:
default = default_list[0]
else:
default = default_list[0][0]
default_count = count - 1
readline.clear_history()
default_list.reverse()
for d in default_list:
if type(d) is str:
readline.add_history(d)
else:
readline.add_history(d[0])
if default_count > 0:
full_prompt = ('{} [{}](+ {} more): '.
format(prompt, default, default_count))
else:
full_prompt = ('{} [{}]: '.
format(prompt, default))
result = input(full_prompt)
if result == '':
return default
else:
return result
开发者ID:bhrebec,项目名称:tennis-datafier,代码行数:34,代码来源:drawsheet.py
示例20: exec_cmd
def exec_cmd(cmdline):
"""Interpret a command."""
cmd, arg = _parse_cmdline(cmdline)
if not cmd:
print("Bad command.")
else:
cmd_callable = get_cmd(cmd)
if not cmd:
print("Type a command. Try 'help'.")
elif cmd_callable:
try:
cmd_callable(arg)
except ImproperArgError as e:
print(str(e))
except UsageError as e:
print("usage: " + cmd + " " + str(e))
except MissingDeckError:
print("No active deck. Create a new deck with the 'deck' " "command.")
except cards.ScrapeError as e:
print("Scrape failed: " + str(e))
if "readline" in sys.modules:
readline.add_history(cmdline)
else:
print("%s is not a command. Try 'help'." % str(cmd))
return True
开发者ID:huangkev,项目名称:deckbuilder,代码行数:25,代码来源:deckbuilder.py
注:本文中的readline.add_history函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论