本文整理汇总了Python中prompt_toolkit.CommandLineInterface.read_input方法的典型用法代码示例。如果您正苦于以下问题:Python CommandLineInterface.read_input方法的具体用法?Python CommandLineInterface.read_input怎么用?Python CommandLineInterface.read_input使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类prompt_toolkit.CommandLineInterface
的用法示例。
在下文中一共展示了CommandLineInterface.read_input方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: main
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
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)
示例2: main
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
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()
示例3: main
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
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)
示例4: main
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
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
示例5: main
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
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!'
示例6: main
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
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)
示例7: _get_input
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
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'
示例8: main
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
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!'
示例9: main
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
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!"
示例10: cli
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
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!')
示例11: get_input
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
def get_input(message, raise_exception_on_abort=False, multiline=False,
is_password=False, vi_mode=False):
"""
Replacement for `raw_input`.
Ask for input, return the answer.
This returns `None` when Ctrl-D was pressed.
"""
layout = Layout(
before_input=DefaultPrompt(message),
input_processors=([PasswordProcessor()] if is_password else []))
cli = CommandLineInterface(
layout=layout,
line=Line(is_multiline=multiline),
key_binding_factories=[(vi_bindings if vi_mode else emacs_bindings)])
on_abort = AbortAction.RAISE_EXCEPTION if raise_exception_on_abort else AbortAction.RETURN_NONE
code = cli.read_input(on_abort=on_abort, on_exit=AbortAction.IGNORE)
if code:
return code.text
示例12: main
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
def main():
cli = CommandLineInterface(layout=Layout(before_input=ClockPrompt()))
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 cli.is_reading_input:
time.sleep(1)
cli.request_redraw()
cli.run_in_executor(run)
cli.onReadInputStart += on_read_start
code_obj = cli.read_input()
print('You said: ' + code_obj.text)
示例13: main
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
def main():
cli = CommandLineInterface(layout=layout, style=TestStyle, line=Line(validator=EmailValidator()))
document = cli.read_input()
print('You said: ' + document.text)
示例14: run_cli
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
def run_cli(self):
pgexecute = self.pgexecute
prompt = '%s> ' % pgexecute.dbname
logger = self.logger
original_less_opts = self.adjust_less_opts()
completer = self.completer
self.refresh_completions()
key_binding_manager = pgcli_bindings(self.vi_mode)
print('Version:', __version__)
print('Chat: https://gitter.im/dbcli/pgcli')
print('Mail: https://groups.google.com/forum/#!forum/pgcli')
print('Home: http://pgcli.com')
layout = Layout(before_input=DefaultPrompt(prompt),
menus=[CompletionsMenu(max_height=10)],
lexer=PostgresLexer,
bottom_toolbars=[PGToolbar(key_binding_manager)])
buf = PGBuffer(always_multiline=self.multi_line, completer=completer,
history=FileHistory(os.path.expanduser('~/.pgcli-history')))
cli = CommandLineInterface(style=style_factory(self.syntax_style),
layout=layout, buffer=buf,
key_bindings_registry=key_binding_manager.registry)
try:
while True:
cli.layout.before_input = DefaultPrompt(prompt)
document = cli.read_input(on_exit=AbortAction.RAISE_EXCEPTION)
# The reason we check here instead of inside the pgexecute is
# because we want to raise the Exit exception which will be
# caught by the try/except block that wraps the pgexecute.run()
# statement.
if quit_command(document.text):
raise Exit
# Keep track of whether or not the query is mutating. In case
# of a multi-statement query, the overall query is considered
# mutating if any one of the component statements is mutating
mutating = False
try:
logger.debug('sql: %r', document.text)
successful = False
# Initialized to [] because res might never get initialized
# if an exception occurs in pgexecute.run(). Which causes
# finally clause to fail.
res = []
start = time()
# Run the query.
res = pgexecute.run(document.text)
duration = time() - start
successful = True
output = []
total = 0
for title, cur, headers, status in res:
logger.debug("headers: %r", headers)
logger.debug("rows: %r", cur)
logger.debug("status: %r", status)
start = time()
threshold = 1000
if (is_select(status) and
cur and cur.rowcount > threshold):
click.secho('The result set has more than %s rows.'
% threshold, fg='red')
if not click.confirm('Do you want to continue?'):
click.secho("Aborted!", err=True, fg='red')
break
output.extend(format_output(title, cur, headers,
status, self.table_format))
end = time()
total += end - start
mutating = mutating or is_mutating(status)
except KeyboardInterrupt:
# Restart connection to the database
pgexecute.connect()
logger.debug("cancelled query, sql: %r", document.text)
click.secho("cancelled query", err=True, fg='red')
except NotImplementedError:
click.secho('Not Yet Implemented.', fg="yellow")
except OperationalError as e:
reconnect = True
if ('server closed the connection' in utf8tounicode(e.args[0])):
reconnect = click.prompt('Connection reset. Reconnect (Y/n)',
show_default=False, type=bool, default=True)
if reconnect:
try:
pgexecute.connect()
click.secho('Reconnected!\nTry the command again.', fg='green')
except OperationalError as e:
click.secho(str(e), err=True, fg='red')
else:
logger.error("sql: %r, error: %r", document.text, e)
logger.error("traceback: %r", traceback.format_exc())
click.secho(str(e), err=True, fg='red')
except Exception as e:
logger.error("sql: %r, error: %r", document.text, e)
logger.error("traceback: %r", traceback.format_exc())
click.secho(str(e), err=True, fg='red')
#.........这里部分代码省略.........
示例15: main
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import read_input [as 别名]
def main():
manager = KeyBindingManager(enable_system_prompt=True)
D = LayoutDimension
layout = HSplit([
VSplit([
Window(width=D(min=15, max=30, preferred=30),
content=FillControl('a', token=Token.A)),
Window(width=D.exact(1),
content=FillControl('|', token=Token.Line)),
Window(content=TokenListControl.static([(Token.HelloWorld, lipsum)])),
Window(width=D.exact(1),
content=FillControl('|', token=Token.Line)),
Window(content=BufferControl(lexer=PythonLexer,
show_line_numbers=Always(),
input_processors=[
DefaultPrompt('python> '),
AfterInput.static(' <python', token=Token.AfterInput),
]),
),
Window(width=D.exact(1),
content=FillControl('|', token=Token.Line)),
HSplit([
Window(width=D(max=40),
height=D.exact(4),
content=FillControl('b', token=Token.B)),
Window(width=D(max=40),
content=FillControl('f', token=Token.F)),
Window(width=D.exact(30),
height=D.exact(2),
content=FillControl('c', token=Token.C)),
]),
#CompletionsMenu(),
]),
Window(height=D.exact(1),
content=FillControl('-', token=Token.Line)),
Window(height=D.exact(3),
content=FillControl('d', token=Token.D)),
SystemToolbar(),
ArgToolbar(),
CompletionsToolbar(),
SearchToolbar(),
])
layout = FloatContainer(
content=layout,
floats=[
Float(xcursor=True,
ycursor=True,
content=VSplit([
Window(width=D.exact(5),
content=FillControl('f', token=Token.F)),
CompletionsMenu(),
])
),
]
)
eventloop = create_eventloop()
cli = CommandLineInterface(eventloop=eventloop,
layout=layout,
style=TestStyle,
key_bindings_registry=manager.registry,
buffer=Buffer(is_multiline=Always(), completer=TestCompleter()))
cli.read_input()
eventloop.close()