def remove_item(self, index):
# readline.remove_history_item() doesn't seem to work. Do it the
# hard way.
#try:
# readline.remove_history_item(i)
#except ValueError:
# pass
buf = []
for i in range(1, self.total + 1):
if i != index:
buf += self.get_item(i)
self.clear_history()
for s in buf:
readline.add_history(s)
python类add_history()的实例源码
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.unlocked_files()
i = 1
for _, _, f in files:
try:
lj = lazyjson.LazyJSON(f, reopen=False)
for cmd in lj['cmds']:
inp = cmd['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):
continue
def handle_return(x, y):
if not delete_input:
rl_done.value = 1
print()
return 0
line = r.get_line_buffer()
if line is not None and len(line) > 0:
r.add_history(line)
rl_set_prompt(c_char_p(b""))
rl_replace_line(c_char_p(b""), 0)
rl_redisplay()
rl_replace_line(c_char_p(line.encode()), 1)
rl_done.value = 1
return 0
def _exec_from_file(self, filename, quiet=False):
previous = ''
for stmt in open(filename):
# - skip over multiple empty lines
stripped = stmt.strip()
if stripped == '' and stripped == previous:
continue
if not quiet:
self.write(cyan("... {}".format(stmt)))
if not stripped.startswith('#'):
line = stmt.strip('\n')
self.push(line)
readline.add_history(line)
previous = stripped
def eventFilter(self, source, event):
# Console Input
if source is self.ui.console_input:
if event.type() == QEvent.KeyPress:
if event.key() in (Qt.Key_Enter, Qt.Key_Return):
command = self.ui.console_input.text()
if command != "":
readline.add_history(
command
)
self.length = readline.get_current_history_length()
self.index = -1
if event.key() == Qt.Key_Up:
if self.index < self.length:
self.index += 1
command = readline.get_history_item(
self.length - self.index
)
self.ui.console_input.setText(
command
)
if event.key() == Qt.Key_Down:
if self.index > 0:
self.index -= 1
command = readline.get_history_item(
self.length - self.index
)
self.ui.console_input.setText(
command
)
return False
return False
def add_item(self, line, force=False):
readline.add_history(line)
def remove_item(self, index):
buf = copy.deepcopy(self.__get_buf())
self.clear_history()
for s in buf:
readline.add_history(s)
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))
def load_history(self):
"""Load saved command history from local history file"""
try:
with file(self.history_file_name, 'r') as f:
for line in f.readlines():
stripped_line = line.strip()
self.history.append(stripped_line)
readline.add_history(stripped_line)
except IOError:
pass # ignore if file cannot be read
def init():
stdout.write("\033[95m----------------------------------------------------------------\n")
if os.getenv('PYSESSION_SAVE_OFF'):
PySession.off()
stdout.write(BANNER_OFF)
elif os.getenv('PYSESSION_SAVE_LOCALLY'):
PySession.local()
stdout.write(BANNER_LOCAL)
else:
stdout.write(BANNER_GIST)
if os.getenv('PYSESSION_SAVE_OFF'):
stdout.write(BANNER_ENABLE)
else:
stdout.write(BANNER_DISABLE)
stdout.write(BANNER_SWITCH)
stdout.write("----------------------------------------------------------------\033[0m\n")
PySession.load_history_urls()
try:
from IPython import get_ipython
PySession.ipython_history = get_ipython().pt_cli.application.buffer.history
PySession.is_ipython = True
except (ImportError, AttributeError):
pass
if PySession.is_ipython:
PySession.start_index = len(PySession.ipython_history)
def custom_hook(shell, etype, evalue, traceback, tb_offset=None):
PySession.wrong_code_lines.append(
len(PySession.ipython_history) - 1)
shell.showtraceback((etype, evalue, traceback),
tb_offset=tb_offset)
get_ipython().set_custom_exc((Exception,), custom_hook)
else:
readline.add_history('') # A hack for a strange bug in 3 < Py <3.5.2
PySession.start_index = readline.get_current_history_length() + 1
default_hook = sys.excepthook
def custom_hook(etype, evalue, traceback):
PySession.wrong_code_lines.append(
readline.get_current_history_length())
default_hook(etype, evalue, traceback)
sys.excepthook = custom_hook
def cmdloop(self, opts):
""" Interactive mode worker function
:param opts: command options
:type opts: options.
"""
self.interactive = True
if not opts.nologo:
CLI.version(self._progname, versioning.__version__,\
versioning.__extracontent__, fileh=sys.stdout)
if opts.debug:
LOGGER.setLevel(logging.DEBUG)
LERR.setLevel(logging.DEBUG)
#**********Handler for GUI tab tab ***************
for section in self._commands:
if section.startswith('_'):
continue
for command in self._commands[section]:
self.commlist.append(command.name)
for item in self.commlist:
if item == "help":
self.candidates[item] = self.commlist
else:
self.candidates[item] = []
self._redobj = TabAndHistoryCompletionClass(dict(self.candidates))
readline.set_completer(self._redobj.main_completer_handler)
readline.parse_and_bind("tab: complete")
#***************************************************
while True:
line = input(versioning.__shortname__+' > ')
readline.add_history(line)
if not len(line):
continue
elif line.endswith(os.linesep):
line.rstrip(os.linesep)
nargv = shlex.split(line, posix=False)
try:
if "login " in line or line == 'login':
self.app.logout()
self.retcode = self._run_command(opts, nargv)
self.check_for_tab_lists(nargv)
except Exception as excp:
self.handle_exceptions(excp)
if self.opts.verbose:
sys.stdout.write(u"REDFISH return code: %s\n" % self.retcode)
return self.retcode