本文整理汇总了Python中prompt_toolkit.history.InMemoryHistory.append方法的典型用法代码示例。如果您正苦于以下问题:Python InMemoryHistory.append方法的具体用法?Python InMemoryHistory.append怎么用?Python InMemoryHistory.append使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类prompt_toolkit.history.InMemoryHistory
的用法示例。
在下文中一共展示了InMemoryHistory.append方法的13个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: HistoryManager
# 需要导入模块: from prompt_toolkit.history import InMemoryHistory [as 别名]
# 或者: from prompt_toolkit.history.InMemoryHistory import append [as 别名]
class HistoryManager(object):
def __init__(self, *args, **kwargs):
super(HistoryManager, self).__init__(*args, **kwargs)
self._history = None
self.last_cmd = None
self.db = None
if HAVE_SQLITE:
dbpath = os.path.join(
save_cache_path('graphcli'),
'history.db'
)
self.db = sqlite3.connect(dbpath)
self.cursor = self.db.cursor()
self.cursor.execute('''
CREATE TABLE IF NOT EXISTS graphcli_history (
ts INT,
cmd TEXT
)
''')
@property
def history(self):
if self._history is None:
self._history = InMemoryHistory()
for cmd in self.read_history():
self._history.append('{0};'.format(cmd))
self.last_cmd = cmd
return self._history
def read_history(self):
if self.db is not None:
commands = self.cursor.execute('''
SELECT cmd FROM graphcli_history
ORDER BY ts DESC
LIMIT ?
''', (self.history_size,))
for row in reversed(list(commands)):
yield row[0]
def add_to_history(self, cmd):
if cmd != self.last_cmd:
if self.db is not None:
ts = int(time())
self.cursor.execute('''
INSERT INTO graphcli_history VALUES (:ts, :cmd)
''', {'ts': ts, 'cmd': cmd})
self.last_cmd = cmd
def close(self):
if self.db is not None:
self.db.commit()
self.db.close()
示例2: init_prompt_toolkit_cli
# 需要导入模块: from prompt_toolkit.history import InMemoryHistory [as 别名]
# 或者: from prompt_toolkit.history.InMemoryHistory import append [as 别名]
def init_prompt_toolkit_cli(self):
if self.simple_prompt:
# Fall back to plain non-interactive output for tests.
# This is very limited, and only accepts a single line.
def prompt():
isp = self.input_splitter
prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
while isp.push_accepts_more():
line = cast_unicode_py2(input(prompt_text))
isp.push(line)
prompt_text = prompt_continuation
return isp.source_reset()
self.prompt_for_code = prompt
return
# Set up keyboard shortcuts
kbmanager = KeyBindingManager.for_prompt(
enable_open_in_editor=self.extra_open_editor_shortcuts,
)
register_ipython_shortcuts(kbmanager.registry, self)
# Pre-populate history from IPython's history database
history = InMemoryHistory()
last_cell = u""
for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
include_latest=True):
# Ignore blank lines and consecutive duplicates
cell = cell.rstrip()
if cell and (cell != last_cell):
history.append(cell)
last_cell = cell
self._style = self._make_style_from_name_or_cls(self.highlighting_style)
self.style = DynamicStyle(lambda: self._style)
editing_mode = getattr(EditingMode, self.editing_mode.upper())
def patch_stdout(**kwargs):
return self.pt_cli.patch_stdout_context(**kwargs)
self._pt_app = create_prompt_application(
editing_mode=editing_mode,
key_bindings_registry=kbmanager.registry,
history=history,
completer=IPythonPTCompleter(shell=self,
patch_stdout=patch_stdout),
enable_history_search=True,
style=self.style,
mouse_support=self.mouse_support,
**self._layout_options()
)
self._eventloop = create_eventloop(self.inputhook)
self.pt_cli = CommandLineInterface(
self._pt_app, eventloop=self._eventloop,
output=create_output(true_color=self.true_color))
示例3: init_prompt_toolkit_cli
# 需要导入模块: from prompt_toolkit.history import InMemoryHistory [as 别名]
# 或者: from prompt_toolkit.history.InMemoryHistory import append [as 别名]
def init_prompt_toolkit_cli(self):
if self.simple_prompt:
# Fall back to plain non-interactive output for tests.
# This is very limited, and only accepts a single line.
def prompt():
return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
self.prompt_for_code = prompt
return
# Set up keyboard shortcuts
kbmanager = KeyBindingManager.for_prompt()
register_ipython_shortcuts(kbmanager.registry, self)
# Pre-populate history from IPython's history database
history = InMemoryHistory()
last_cell = u""
for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
include_latest=True):
# Ignore blank lines and consecutive duplicates
cell = cell.rstrip()
if cell and (cell != last_cell):
history.append(cell)
last_cell = cell
self._style = self._make_style_from_name_or_cls(self.highlighting_style)
style = DynamicStyle(lambda: self._style)
editing_mode = getattr(EditingMode, self.editing_mode.upper())
self._pt_app = create_prompt_application(
editing_mode=editing_mode,
key_bindings_registry=kbmanager.registry,
history=history,
completer=IPythonPTCompleter(shell=self),
enable_history_search=True,
style=style,
mouse_support=self.mouse_support,
**self._layout_options()
)
self._eventloop = create_eventloop(self.inputhook)
self.pt_cli = CommandLineInterface(
self._pt_app, eventloop=self._eventloop,
output=create_output(true_color=self.true_color))
示例4: main
# 需要导入模块: from prompt_toolkit.history import InMemoryHistory [as 别名]
# 或者: from prompt_toolkit.history.InMemoryHistory import append [as 别名]
def main():
# Create some history first. (Easy for testing.)
history = InMemoryHistory()
history.append("import os")
history.append('print("hello")')
history.append('print("world")')
history.append("import path")
# Print help.
print("This CLI has up-arrow partial string matching enabled.")
print('Type for instance "pri" followed by up-arrow and you')
print('get the last items starting with "pri".')
print("Press Control-C to retry. Control-D to exit.")
print()
text = prompt("Say something: ", history=history, enable_history_search=Always(), on_abort=AbortAction.RETRY)
print("You said: %s" % text)
示例5: main
# 需要导入模块: from prompt_toolkit.history import InMemoryHistory [as 别名]
# 或者: from prompt_toolkit.history.InMemoryHistory import append [as 别名]
def main():
# Create some history first. (Easy for testing.)
history = InMemoryHistory()
history.append('import os')
history.append('print("hello")')
history.append('print("world")')
history.append('import path')
# Print help.
print('This CLI has fish-style auto-suggestion enable.')
print('Type for instance "pri", then you\'ll see a suggestion.')
print('Press the right arrow to insert the suggestion.')
print('Press Control-C to retry. Control-D to exit.')
print()
text = prompt('Say something: ', history=history,
auto_suggest=AutoSuggestFromHistory(),
enable_history_search=True,
on_abort=AbortAction.RETRY)
print('You said: {0!s}'.format(text))
示例6: init_prompt_toolkit_cli
# 需要导入模块: from prompt_toolkit.history import InMemoryHistory [as 别名]
# 或者: from prompt_toolkit.history.InMemoryHistory import append [as 别名]
def init_prompt_toolkit_cli(self):
if ('IPY_TEST_SIMPLE_PROMPT' in os.environ) or not sys.stdin.isatty():
# Fall back to plain non-interactive output for tests.
# This is very limited, and only accepts a single line.
def prompt():
return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
self.prompt_for_code = prompt
return
kbmanager = KeyBindingManager.for_prompt(enable_vi_mode=self.vi_mode)
insert_mode = ViStateFilter(kbmanager.get_vi_state, InputMode.INSERT)
# Ctrl+J == Enter, seemingly
@kbmanager.registry.add_binding(Keys.ControlJ,
filter=(HasFocus(DEFAULT_BUFFER)
& ~HasSelection()
& insert_mode
))
def _(event):
b = event.current_buffer
d = b.document
if not (d.on_last_line or d.cursor_position_row >= d.line_count
- d.empty_line_count_at_the_end()):
b.newline()
return
status, indent = self.input_splitter.check_complete(d.text)
if (status != 'incomplete') and b.accept_action.is_returnable:
b.accept_action.validate_and_handle(event.cli, b)
else:
b.insert_text('\n' + (' ' * (indent or 0)))
@kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
event.current_buffer.reset()
@kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER))
def _(event):
if event.current_buffer.document.text:
event.current_buffer.reset()
else:
event.cli.push_focus(DEFAULT_BUFFER)
supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
@kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend)
def _(event):
event.cli.suspend_to_background()
@Condition
def cursor_in_leading_ws(cli):
before = cli.application.buffer.document.current_line_before_cursor
return (not before) or before.isspace()
# Ctrl+I == Tab
@kbmanager.registry.add_binding(Keys.ControlI,
filter=(HasFocus(DEFAULT_BUFFER)
& ~HasSelection()
& insert_mode
& cursor_in_leading_ws
))
def _(event):
event.current_buffer.insert_text(' ' * 4)
# Pre-populate history from IPython's history database
history = InMemoryHistory()
last_cell = u""
for _, _, cell in self.history_manager.get_tail(self.history_load_length,
include_latest=True):
# Ignore blank lines and consecutive duplicates
cell = cell.rstrip()
if cell and (cell != last_cell):
history.append(cell)
self._style = self._make_style_from_name(self.highlighting_style)
style = DynamicStyle(lambda: self._style)
self._app = create_prompt_application(
key_bindings_registry=kbmanager.registry,
history=history,
completer=IPythonPTCompleter(self.Completer),
enable_history_search=True,
style=style,
mouse_support=self.mouse_support,
**self._layout_options()
)
self.pt_cli = CommandLineInterface(self._app,
eventloop=create_eventloop(self.inputhook))
示例7: init_prompt_toolkit_cli
# 需要导入模块: from prompt_toolkit.history import InMemoryHistory [as 别名]
# 或者: from prompt_toolkit.history.InMemoryHistory import append [as 别名]
#.........这里部分代码省略.........
- d.empty_line_count_at_the_end()):
b.newline()
return
status, indent = self.input_splitter.check_complete(d.text)
if (status != 'incomplete') and b.accept_action.is_returnable:
b.accept_action.validate_and_handle(event.cli, b)
else:
b.insert_text('\n' + (' ' * (indent or 0)))
@kbmanager.registry.add_binding(Keys.ControlP, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)))
def _previous_history_or_previous_completion(event):
"""
Control-P in vi edit mode on readline is history next, unlike default prompt toolkit.
If completer is open this still select previous completion.
"""
event.current_buffer.auto_up()
@kbmanager.registry.add_binding(Keys.ControlN, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)))
def _next_history_or_next_completion(event):
"""
Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit.
If completer is open this still select next completion.
"""
event.current_buffer.auto_down()
@kbmanager.registry.add_binding(Keys.ControlG, filter=(
HasFocus(DEFAULT_BUFFER) & HasCompletions()
))
def _dismiss_completion(event):
b = event.current_buffer
if b.complete_state:
b.cancel_completion()
@kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER))
def _reset_buffer(event):
b = event.current_buffer
if b.complete_state:
b.cancel_completion()
else:
b.reset()
@kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER))
def _reset_search_buffer(event):
if event.current_buffer.document.text:
event.current_buffer.reset()
else:
event.cli.push_focus(DEFAULT_BUFFER)
supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP'))
@kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend)
def _suspend_to_bg(event):
event.cli.suspend_to_background()
@Condition
def cursor_in_leading_ws(cli):
before = cli.application.buffer.document.current_line_before_cursor
return (not before) or before.isspace()
# Ctrl+I == Tab
@kbmanager.registry.add_binding(Keys.ControlI,
filter=(HasFocus(DEFAULT_BUFFER)
& ~HasSelection()
& insert_mode
& cursor_in_leading_ws
))
def _indent_buffer(event):
event.current_buffer.insert_text(' ' * 4)
# Pre-populate history from IPython's history database
history = InMemoryHistory()
last_cell = u""
for __, ___, cell in self.history_manager.get_tail(self.history_load_length,
include_latest=True):
# Ignore blank lines and consecutive duplicates
cell = cell.rstrip()
if cell and (cell != last_cell):
history.append(cell)
self._style = self._make_style_from_name(self.highlighting_style)
style = DynamicStyle(lambda: self._style)
editing_mode = getattr(EditingMode, self.editing_mode.upper())
self._app = create_prompt_application(
editing_mode=editing_mode,
key_bindings_registry=kbmanager.registry,
history=history,
completer=IPythonPTCompleter(self.Completer),
enable_history_search=True,
style=style,
mouse_support=self.mouse_support,
**self._layout_options()
)
self._eventloop = create_eventloop(self.inputhook)
self.pt_cli = CommandLineInterface(self._app, eventloop=self._eventloop)
示例8: init_prompt_toolkit_cli
# 需要导入模块: from prompt_toolkit.history import InMemoryHistory [as 别名]
# 或者: from prompt_toolkit.history.InMemoryHistory import append [as 别名]
def init_prompt_toolkit_cli(self):
if 'JUPYTER_CONSOLE_TEST' in os.environ:
# Simple restricted interface for tests so we can find prompts with
# pexpect. Multi-line input not supported.
def prompt():
return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
self.prompt_for_code = prompt
self.print_out_prompt = \
lambda: print('Out[%d]: ' % self.execution_count, end='')
return
kbmanager = KeyBindingManager.for_prompt()
insert_mode = ViInsertMode() | EmacsInsertMode()
# Ctrl+J == Enter, seemingly
@kbmanager.registry.add_binding(Keys.ControlJ,
filter=(HasFocus(DEFAULT_BUFFER)
& ~HasSelection()
& insert_mode
))
def _(event):
b = event.current_buffer
d = b.document
if not (d.on_last_line or d.cursor_position_row >= d.line_count
- d.empty_line_count_at_the_end()):
b.newline()
return
more, indent = self.check_complete(d.text)
if (not more) and b.accept_action.is_returnable:
b.accept_action.validate_and_handle(event.cli, b)
else:
b.insert_text('\n' + indent)
@kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER))
def _(event):
event.current_buffer.reset()
# Pre-populate history from IPython's history database
history = InMemoryHistory()
last_cell = u""
for _, _, cell in self.history_manager.get_tail(self.history_load_length,
include_latest=True):
# Ignore blank lines and consecutive duplicates
cell = cell.rstrip()
if cell and (cell != last_cell):
history.append(cell)
style_overrides = {
Token.Prompt: '#009900',
Token.PromptNum: '#00ff00 bold',
Token.OutPrompt: '#ff2200',
Token.OutPromptNum: '#ff0000 bold',
}
if self.highlighting_style:
style_cls = get_style_by_name(self.highlighting_style)
else:
style_cls = get_style_by_name('default')
# The default theme needs to be visible on both a dark background
# and a light background, because we can't tell what the terminal
# looks like. These tweaks to the default theme help with that.
style_overrides.update({
Token.Number: '#007700',
Token.Operator: 'noinherit',
Token.String: '#BB6622',
Token.Name.Function: '#2080D0',
Token.Name.Class: 'bold #2080D0',
Token.Name.Namespace: 'bold #2080D0',
})
style_overrides.update(self.highlighting_style_overrides)
style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
style_dict=style_overrides)
editing_mode = getattr(EditingMode, self.editing_mode.upper())
langinfo = self.kernel_info.get('language_info', {})
lexer = langinfo.get('pygments_lexer', langinfo.get('name', 'text'))
app = create_prompt_application(multiline=True,
editing_mode=editing_mode,
lexer=PygmentsLexer(get_pygments_lexer(lexer)),
get_prompt_tokens=self.get_prompt_tokens,
get_continuation_tokens=self.get_continuation_tokens,
key_bindings_registry=kbmanager.registry,
history=history,
completer=JupyterPTCompleter(self.Completer),
enable_history_search=True,
style=style,
)
self._eventloop = create_eventloop()
self.pt_cli = CommandLineInterface(app,
eventloop=self._eventloop,
output=create_output(true_color=self.true_color),
)
示例9: init_prompt_toolkit_cli
# 需要导入模块: from prompt_toolkit.history import InMemoryHistory [as 别名]
# 或者: from prompt_toolkit.history.InMemoryHistory import append [as 别名]
def init_prompt_toolkit_cli(self):
if not sys.stdin.isatty():
# Piped input - e.g. for tests. Fall back to plain non-interactive
# output. This is very limited, and only accepts a single line.
def prompt():
return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
self.prompt_for_code = prompt
return
kbmanager = KeyBindingManager.for_prompt(enable_vi_mode=self.vi_mode)
insert_mode = ViStateFilter(kbmanager.get_vi_state, InputMode.INSERT)
# Ctrl+J == Enter, seemingly
@kbmanager.registry.add_binding(Keys.ControlJ,
filter=(HasFocus(DEFAULT_BUFFER)
& ~HasSelection()
& insert_mode
))
def _(event):
b = event.current_buffer
d = b.document
if not (d.on_last_line or d.cursor_position_row >= d.line_count
- d.empty_line_count_at_the_end()):
b.newline()
return
status, indent = self.input_splitter.check_complete(d.text)
if (status != 'incomplete') and b.accept_action.is_returnable:
b.accept_action.validate_and_handle(event.cli, b)
else:
b.insert_text('\n' + (' ' * (indent or 0)))
@kbmanager.registry.add_binding(Keys.ControlC)
def _(event):
event.current_buffer.reset()
# Pre-populate history from IPython's history database
history = InMemoryHistory()
last_cell = u""
for _, _, cell in self.history_manager.get_tail(self.history_load_length,
include_latest=True):
# Ignore blank lines and consecutive duplicates
cell = cell.rstrip()
if cell and (cell != last_cell):
history.append(cell)
style_overrides = {
Token.Prompt: '#009900',
Token.PromptNum: '#00ff00 bold',
}
if self.highlighting_style:
style_cls = get_style_by_name(self.highlighting_style)
else:
style_cls = get_style_by_name('default')
# The default theme needs to be visible on both a dark background
# and a light background, because we can't tell what the terminal
# looks like. These tweaks to the default theme help with that.
style_overrides.update({
Token.Number: '#007700',
Token.Operator: 'noinherit',
Token.String: '#BB6622',
Token.Name.Function: '#2080D0',
Token.Name.Class: 'bold #2080D0',
Token.Name.Namespace: 'bold #2080D0',
})
style_overrides.update(self.highlighting_style_overrides)
style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
style_dict=style_overrides)
app = create_prompt_application(multiline=True,
lexer=PygmentsLexer(Python3Lexer if PY3 else PythonLexer),
get_prompt_tokens=self.get_prompt_tokens,
get_continuation_tokens=self.get_continuation_tokens,
key_bindings_registry=kbmanager.registry,
history=history,
completer=IPythonPTCompleter(self.Completer),
enable_history_search=True,
style=style,
mouse_support=self.mouse_support,
)
self.pt_cli = CommandLineInterface(app,
eventloop=create_eventloop(self.inputhook))
示例10: AWSShell
# 需要导入模块: from prompt_toolkit.history import InMemoryHistory [as 别名]
# 或者: from prompt_toolkit.history.InMemoryHistory import append [as 别名]
#.........这里部分代码省略.........
self.config_obj.write()
@property
def cli(self):
if self._cli is None or self.refresh_cli:
self._cli = self.create_cli_interface(self.show_completion_columns)
self.refresh_cli = False
return self._cli
def run(self):
while True:
try:
document = self.cli.run(reset_current_buffer=True)
text = document.text
except InputInterrupt:
pass
except (KeyboardInterrupt, EOFError):
self.save_config()
break
else:
if text.startswith('.'):
# These are special commands (dot commands) that are
# interpreted by the aws-shell directly and typically used
# to modify some type of behavior in the aws-shell.
result = self._dot_cmd.handle_cmd(text, application=self)
if result is EXIT_REQUESTED:
break
else:
if text.startswith('!'):
# Then run the rest as a normally shell command.
full_cmd = text[1:]
else:
full_cmd = 'aws ' + text
self.history.append(full_cmd)
self.current_docs = u''
self.cli.buffers['clidocs'].reset(
initial_document=Document(self.current_docs,
cursor_position=0))
self.cli.request_redraw()
p = subprocess.Popen(full_cmd, shell=True, env=self._env)
p.communicate()
def stop_input_and_refresh_cli(self):
"""Stop input by raising an `InputInterrupt`, forces a cli refresh.
The cli refresh is necessary because changing options such as key
bindings, single vs multi column menu completions, and the help pane
all require a rebuild.
:raises: :class:`InputInterrupt <exceptions.InputInterrupt>`.
"""
self.refresh_cli = True
self.cli.request_redraw()
raise InputInterrupt
def create_layout(self, display_completions_in_columns, toolbar):
from awsshell.lexer import ShellLexer
lexer = ShellLexer
if self.config_section['theme'] == 'none':
lexer = None
return create_default_layout(
self, u'aws> ', lexer=lexer, reserve_space_for_menu=True,
display_completions_in_columns=display_completions_in_columns,
get_bottom_toolbar_tokens=toolbar.handler)
示例11: _history
# 需要导入模块: from prompt_toolkit.history import InMemoryHistory [as 别名]
# 或者: from prompt_toolkit.history.InMemoryHistory import append [as 别名]
def _history():
h = InMemoryHistory()
h.append('line1 first input')
h.append('line2 second input')
h.append('line3 third input')
return h
示例12: _history
# 需要导入模块: from prompt_toolkit.history import InMemoryHistory [as 别名]
# 或者: from prompt_toolkit.history.InMemoryHistory import append [as 别名]
def _history():
" Prefilled history. "
history = InMemoryHistory()
history.append('alpha beta gamma delta')
history.append('one two three four')
return history
示例13: InMemoryHistory
# 需要导入模块: from prompt_toolkit.history import InMemoryHistory [as 别名]
# 或者: from prompt_toolkit.history.InMemoryHistory import append [as 别名]
from prompt_toolkit import prompt
from prompt_toolkit.history import InMemoryHistory
from prompt_toolkit.auto_suggest import AutoSuggestFromHistory
history = InMemoryHistory()
for word in ["apple", "banana", "orange", "grape", "pineapple"]:
history.append(word)
while True:
text = prompt('> ', history=history, auto_suggest=AutoSuggestFromHistory())
print('You said: ', text)