本文整理汇总了Python中prompt_toolkit.history.InMemoryHistory类的典型用法代码示例。如果您正苦于以下问题:Python InMemoryHistory类的具体用法?Python InMemoryHistory怎么用?Python InMemoryHistory使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了InMemoryHistory类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: HistoryManager
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
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__
def __init__(self, completer, model_completer, docs,
input=None, output=None):
self.completer = completer
self.model_completer = model_completer
self.history = InMemoryHistory()
self.file_history = FileHistory(build_config_file_path('history'))
self._cli = None
self._docs = docs
self.current_docs = u''
self.refresh_cli = False
self.key_manager = None
self._dot_cmd = DotCommandHandler()
self._env = os.environ.copy()
self._profile = None
self._input = input
self._output = output
# These attrs come from the config file.
self.config_obj = None
self.config_section = None
self.enable_vi_bindings = None
self.show_completion_columns = None
self.show_help = None
self.theme = None
self.load_config()
示例4: init_prompt_toolkit_cli
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 = input(prompt_text)
isp.push(line)
prompt_text = prompt_continuation
return isp.source_reset()
self.prompt_for_code = prompt
return
# Set up keyboard shortcuts
key_bindings = create_ipython_shortcuts(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_string(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())
self.pt_app = PromptSession(
editing_mode=editing_mode,
key_bindings=key_bindings,
history=history,
completer=IPythonPTCompleter(shell=self),
enable_history_search = self.enable_history_search,
style=self.style,
include_default_pygments_style=False,
mouse_support=self.mouse_support,
enable_open_in_editor=self.extra_open_editor_shortcuts,
color_depth=(ColorDepth.TRUE_COLOR if self.true_color else None),
**self._extra_prompt_options())
示例5: main
def main():
# Create some history first. (Easy for testing.)
history = InMemoryHistory()
history.append_string('import os')
history.append_string('print("hello")')
history.append_string('print("world")')
history.append_string('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()
session = PromptSession(
history=history,
auto_suggest=AutoSuggestFromHistory(),
enable_history_search=True)
while True:
try:
text = session.prompt('Say something: ')
except KeyboardInterrupt:
pass # Ctrl-C pressed. Try again.
else:
break
print('You said: %s' % text)
示例6: main
def main():
# Create some history first. (Easy for testing.)
history = InMemoryHistory()
history.append_string('import os')
history.append_string('print("hello")')
history.append_string('print("world")')
history.append_string('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()
session = PromptSession(history=history, enable_history_search=True)
while True:
try:
text = session.prompt('Say something: ')
except KeyboardInterrupt:
pass # Ctrl-C pressed. Try again.
else:
break
print('You said: %s' % text)
示例7: history
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
示例8: init_prompt_toolkit_cli
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))
示例9: __init__
def __init__(self, completer, model_completer, docs):
self.completer = completer
self.model_completer = model_completer
self.history = InMemoryHistory()
self.file_history = FileHistory(build_config_file_path('history'))
self._cli = None
self._docs = docs
self.current_docs = u''
self.refresh_cli = False
self._dot_cmd = DotCommandHandler()
self.load_config()
示例10: main
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)
示例11: main
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))
示例12: _history
def _history():
h = InMemoryHistory()
h.append_string('line1 first input')
h.append_string('line2 second input')
h.append_string('line3 third input')
return h
示例13: InMemoryHistory
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)
示例14: _history
def _history():
" Prefilled history. "
history = InMemoryHistory()
history.append_string('alpha beta gamma delta')
history.append_string('one two three four')
return history
示例15: init_prompt_toolkit_cli
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))