本文整理汇总了Python中prompt_toolkit.CommandLineInterface类的典型用法代码示例。如果您正苦于以下问题:Python CommandLineInterface类的具体用法?Python CommandLineInterface怎么用?Python CommandLineInterface使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了CommandLineInterface类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
def main():
eventloop = create_eventloop()
cli = CommandLineInterface(layout=Window(BufferControl(input_processors=[ClockPrompt()])),
eventloop=eventloop)
done = [False] # Non local
def on_read_start():
"""
This function is called when we start reading at the input.
(Actually the start of the read-input event loop.)
"""
# Following function should be run in the background.
# We do it by using an executor thread from the `CommandLineInterface`
# instance.
def run():
# Send every second a redraw request.
while not done[0]:
time.sleep(1)
cli.request_redraw()
cli.eventloop.run_in_executor(run)
def on_read_end():
done[0] = True
cli.onReadInputStart += on_read_start
cli.onReadInputEnd += on_read_end
code_obj = cli.read_input()
print('You said: %s' % code_obj.text)
eventloop.close()
示例2: AqPrompt
class AqPrompt(object):
def __init__(self, parser, engine, options=None):
self.parser = parser
self.engine = engine
self.options = options if options is not None else {}
util.ensure_data_dir_exists()
application = create_prompt_application(
message='> ',
lexer=PygmentsLexer(SqlLexer),
history=FileHistory(os.path.expanduser('~/.aq/history')),
completer=AqCompleter(schemas=engine.available_schemas, tables=engine.available_tables),
auto_suggest=AutoSuggestFromHistory(),
validator=QueryValidator(parser),
on_abort=AbortAction.RETRY,
)
loop = create_eventloop()
self.cli = CommandLineInterface(application=application, eventloop=loop)
self.patch_context = self.cli.patch_stdout_context()
def prompt(self):
with self.patch_context:
return self.cli.run(reset_current_buffer=True).text
def update_with_result(self, query_metadata):
# TODO
pass
示例3: main
def main():
layout = Layout(
left_margin=LeftMarginWithLineNumbers(),
before_input=DefaultPrompt(text='Before input >> '),
after_input=Prompt(' << after input'),
top_toolbars=[
TextToolbar('This is a top toolbar\n(second line)\n(third line)', token=Token.TopToolbar1, height=3),
TextToolbar('This is another top toolbar', token=Token.TopToolbar2),
],
bottom_toolbars=[
ArgToolbar(),
SearchToolbar(),
CompletionsToolbar(),
TextToolbar('This is a bottom toolbar', token=Token.BottomToolbar1),
TextToolbar('This is a multiline bottom toolbar\n(second line)\n(third line)', token=Token.BottomToolbar2, height=3),
],
show_tildes=True,
menus=[CompletionsMenu()])
cli = CommandLineInterface(layout=layout,
style=TestStyle,
line=Line(is_multiline=True, completer=TestCompleter()))
code_obj = cli.read_input(initial_value=lipsum)
print('You said: ' + code_obj.text)
示例4: main
def main():
cli = CommandLineInterface(layout=Layout(
before_input=DefaultPrompt('Enter HTML: '),
lexer=HtmlLexer))
html_code_obj = cli.read_input()
print('You said: ' + html_code_obj.text)
示例5: main
def main():
cli = CommandLineInterface(line=Line(history=FileHistory('.example-history-file')))
try:
while True:
document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)
print('You said: ' + document.text)
except Exit:
pass
示例6: run
def run(self):
neo4j = Neo4j(self.host, self.port, self.username, self.password)
try:
labels = neo4j.labels()
relationship_types = neo4j.relationship_types()
properties = neo4j.properties()
except Unauthorized:
print("Unauthorized. See cycli --help for authorization instructions.")
return
except SocketError:
print("Connection refused. Is Neo4j turned on?")
return
completer = CypherCompleter(labels, relationship_types, properties)
layout = create_default_layout(
lexer=CypherLexer,
get_prompt_tokens=get_tokens,
reserve_space_for_menu=True
)
buff = CypherBuffer(
history=History(),
completer=completer,
complete_while_typing=Always()
)
application = Application(
style=CypherStyle,
buffer=buff,
layout=layout,
on_exit=AbortAction.RAISE_EXCEPTION
)
cli = CommandLineInterface(application=application, eventloop=create_eventloop())
try:
while True:
document = cli.run()
query = document.text
if query in ["quit", "exit"]:
raise Exception
elif query == "help":
print(help_text())
else:
results = neo4j.cypher(query)
print(results)
except Exception:
print("Goodbye!")
示例7: main
def main():
layout = Layout(before_input=DefaultPrompt('> '), lexer=HyLexer, menus=[CompletionMenu()])
line = Line(completer=HyCompleter())
cli = CommandLineInterface(layout=layout, line=line)
try:
while True:
code_obj = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)
print 'You entered:', code_obj.text
except Exit:
print 'GoodBye!'
示例8: main
def main():
cli = CommandLineInterface(style=AnimalStyle,
layout=Layout(before_input=DefaultPrompt('Give some animals: '),
menus=[CompletionMenu()]),
line=Line(completer=AnimalCompleter()),
create_async_autocompleters=True,
)
print('Press tab to complete')
code_obj = cli.read_input()
print('You said: ' + code_obj.text)
示例9: _get_input
def _get_input(self):
"""
Read PDB input. Return input text.
"""
g = self._create_grammar()
cli = CommandLineInterface(
layout=Layout(
before_input=PdbPrompt(self._get_current_pdb_commands()),
show_tildes=True,
min_height=15,
lexer=GrammarLexer(
g,
tokens={'pdb_command': Token.PdbCommand},
lexers={'python_code': PythonLexer}
),
after_input=CompletionHint(),
menus=[CompletionsMenu()],
top_toolbars=[],
bottom_toolbars=[
SystemToolbar(),
ArgToolbar(),
SearchToolbar(),
SourceCodeToolbar(weakref.ref(self)),
ValidationToolbar(),
ShortcutsToolbar(),
PdbStatusToolbar(weakref.ref(self)),
]),
line=Line(
completer=GrammarCompleter(g, completers={
'enabled_breakpoint': BreakPointListCompleter(only_enabled=True),
'disabled_breakpoint': BreakPointListCompleter(only_disabled=True),
'alias_name': AliasCompleter(self),
'python_code': PythonCompleter(lambda: self.curframe.f_globals, lambda: self.curframe.f_locals),
'breakpoint': BreakPointListCompleter(),
'pdb_command': PdbCommandsCompleter(self),
'python_file': PythonFileCompleter(),
'python_function': PythonFunctionCompleter(self),
}),
history=self._cli_history,
validator=GrammarValidator(g, {
'python_code': PythonValidator()
}),
),
key_binding_factories=[emacs_bindings, custom_pdb_key_bindings],
style=PdbStyle)
try:
return cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION).text
except Exit:
# Turn Control-D key press into a 'quit' command.
return 'q'
示例10: loop
def loop(cmd, history_file):
key_binding_manager = KeyBindingManager(
enable_search=True,
enable_abort_and_exit_bindings=True
)
layout = create_prompt_layout(
message=u'cr> ',
multiline=True,
lexer=SqlLexer,
extra_input_processors=[
ConditionalProcessor(
processor=HighlightMatchingBracketProcessor(chars='[](){}'),
filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
]
)
buffer = CrashBuffer(
history=TruncatedFileHistory(history_file, max_length=MAX_HISTORY_LENGTH),
accept_action=AcceptAction.RETURN_DOCUMENT,
completer=SQLCompleter(cmd)
)
buffer.complete_while_typing = lambda cli=None: cmd.should_autocomplete()
application = Application(
layout=layout,
buffer=buffer,
style=PygmentsStyle.from_defaults(pygments_style_cls=CrateStyle),
key_bindings_registry=key_binding_manager.registry,
editing_mode=_get_editing_mode(),
on_exit=AbortAction.RAISE_EXCEPTION,
on_abort=AbortAction.RETRY,
)
eventloop = create_eventloop()
output = create_output()
cli = CommandLineInterface(
application=application,
eventloop=eventloop,
output=output
)
def get_num_columns_override():
return output.get_size().columns
cmd.get_num_columns = get_num_columns_override
while True:
try:
doc = cli.run(reset_current_buffer=True)
if doc:
cmd.process(doc.text)
except KeyboardInterrupt:
cmd.logger.warn("Query not cancelled. Run KILL <jobId> to cancel it")
except EOFError:
cmd.logger.warn(u'Bye!')
return
示例11: main
def main(database):
connection = sqlite3.connect(database)
layout = Layout(before_input=DefaultPrompt('> '),
lexer=SqlLexer, menus=[CompletionMenu()])
line = Line(completer=SqlCompleter())
cli = CommandLineInterface(style=DocumentStyle, layout=layout, line=line)
try:
while True:
document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)
with connection:
messages = connection.execute(document.text)
for message in messages:
print message
except Exit:
print 'GoodBye!'
示例12: _create_cli
def _create_cli(self):
"""Create the prompt_toolkit's CommandLineInterface."""
history = FileHistory(os.path.expanduser('~/.haxornewshistory'))
toolbar = Toolbar(lambda: self.paginate_comments)
layout = create_default_layout(
message=u'haxor> ',
reserve_space_for_menu=True,
get_bottom_toolbar_tokens=toolbar.handler,
)
cli_buffer = Buffer(
history=history,
auto_suggest=AutoSuggestFromHistory(),
enable_history_search=True,
completer=self.completer,
complete_while_typing=Always(),
accept_action=AcceptAction.RETURN_DOCUMENT)
self.key_manager = self._create_key_manager()
style_factory = StyleFactory(self.theme)
application = Application(
mouse_support=False,
style=style_factory.style,
layout=layout,
buffer=cli_buffer,
key_bindings_registry=self.key_manager.manager.registry,
on_exit=AbortAction.RAISE_EXCEPTION,
on_abort=AbortAction.RETRY,
ignore_case=True)
eventloop = create_eventloop()
self.cli = CommandLineInterface(
application=application,
eventloop=eventloop)
示例13: main
def main():
layout = Layout(before_input=DefaultPrompt("> "), menus=[CompletionMenu()])
line = Line(RESTCompleter())
cli = CommandLineInterface(style=DocumentStyle, layout=layout, line=line)
try:
while True:
document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)
input_args = document.text.split(" ")
if len(input_args) < 2:
raise AssertionError("Must provide at least a method and a url")
response = process_request(input_args)
print "Response:", response.json()
except Exit:
print "GoodBye!"
示例14: create_cli
def create_cli(self):
"""Creates the prompt_toolkit's CommandLineInterface.
Long description.
Args:
* None.
Returns:
None.
"""
history = FileHistory(os.path.expanduser('~/.saws-history'))
toolbar = Toolbar(self.get_color,
self.get_fuzzy_match,
self.get_shortcut_match)
layout = create_default_layout(
message='saws> ',
reserve_space_for_menu=True,
lexer=CommandLexer,
get_bottom_toolbar_tokens=toolbar.handler,
extra_input_processors=[
ConditionalProcessor(
processor=HighlightMatchingBracketProcessor(
chars='[](){}'),
filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
]
)
cli_buffer = Buffer(
history=history,
completer=self.completer,
complete_while_typing=Always(),
accept_action=AcceptAction.RETURN_DOCUMENT)
self.key_manager = KeyManager(
self.set_color,
self.get_color,
self.set_fuzzy_match,
self.get_fuzzy_match,
self.set_shortcut_match,
self.get_shortcut_match,
self.refresh_resources,
self.handle_docs)
style_factory = StyleFactory(self.theme)
application = Application(
mouse_support=False,
style=style_factory.style,
layout=layout,
buffer=cli_buffer,
key_bindings_registry=self.key_manager.manager.registry,
on_exit=AbortAction.RAISE_EXCEPTION,
on_abort=AbortAction.RETRY,
ignore_case=True)
eventloop = create_eventloop()
self.aws_cli = CommandLineInterface(
application=application,
eventloop=eventloop)
示例15: cli
def cli(database, user, password, host, port):
from pgcli import __file__ as package_root
package_root = os.path.dirname(package_root)
default_config = os.path.join(package_root, 'pgclirc')
# Write default config.
write_default_config(default_config, '~/.pgclirc')
# Load config.
config = load_config('~/.pgclirc')
# Connect to the database.
try:
pgexecute = PGExecute(database, user, password, host, port)
except Exception as e:
click.secho(e.message, err=True, fg='red')
exit(1)
layout = Layout(before_input=DefaultPrompt('%s> ' % database),
menus=[CompletionsMenu()],
lexer=SqlLexer)
completer = PGCompleter(config.getboolean('main', 'smart_completion'))
completer.extend_special_commands(pgexecute.special_commands.keys())
completer.extend_table_names(pgexecute.tables())
completer.extend_column_names(pgexecute.all_columns())
line = Line(completer=completer,
history=FileHistory(os.path.expanduser('~/.pgcli-history')))
cli = CommandLineInterface(style=PGStyle, layout=layout, line=line)
try:
while True:
document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)
try:
rows, headers, status = pgexecute.run(document.text)
if rows:
print(tabulate(rows, headers, tablefmt='psql'))
print(status)
except Exception as e:
click.secho(e.message, err=True, fg='red')
except Exit:
print ('GoodBye!')