本文整理汇总了Python中prompt_toolkit.CommandLineInterface.run方法的典型用法代码示例。如果您正苦于以下问题:Python CommandLineInterface.run方法的具体用法?Python CommandLineInterface.run怎么用?Python CommandLineInterface.run使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类prompt_toolkit.CommandLineInterface
的用法示例。
在下文中一共展示了CommandLineInterface.run方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: AqPrompt
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
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
示例2: run
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
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!")
示例3: SaltCli
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
class SaltCli(object):
"""
The CLI implementation.
"""
def __init__(self):
self.logger = logging.getLogger(__name__)
self.id_completer = WordCompleter([
'id1', 'id2', 'id3'
])
def run_cli(self):
"""
Run the main loop
"""
print(u'Version:', __version__)
print(u'Home: https://github.com/glasslion/saltcli')
history = FileHistory(os.path.expanduser('~/.saltcli-history'))
layout = create_prompt_layout(
message=u'saltcli> ',
)
application = Application(
layout=layout
)
eventloop = create_eventloop()
self.cli = CommandLineInterface(
application=application,
eventloop=eventloop)
while True:
try:
document = self.cli.run()
if quit_command(document.text):
raise EOFError
except KeyboardInterrupt:
# user pressed Ctrl + C
click.echo('')
except EOFError:
break
except Exception as ex:
self.logger.debug('Exception: %r.', ex)
self.logger.error("traceback: %r", traceback.format_exc())
click.secho("{0}".format(ex), fg='red')
break
print('Goodbye!')
示例4: loop
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
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
示例5: MyCli
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
#.........这里部分代码省略.........
'Execute commands from file.', aliases=('\\.',))
special.register_special_command(self.change_prompt_format, 'prompt',
'\\R', 'Change prompt format.', aliases=('\\R',), case_sensitive=True)
def change_table_format(self, arg, **_):
if not arg in table_formats():
msg = "Table type %s not yet implemented. Allowed types:" % arg
for table_type in table_formats():
msg += "\n\t%s" % table_type
yield (None, None, None, msg)
else:
self.table_format = arg
yield (None, None, None, "Changed table Type to %s" % self.table_format)
def change_db(self, arg, **_):
if arg is None:
self.sqlexecute.connect()
else:
self.sqlexecute.connect(database=arg)
yield (None, None, None, 'You are now connected to database "%s" as '
'user "%s"' % (self.sqlexecute.dbname, self.sqlexecute.user))
def execute_from_file(self, arg, **_):
if not arg:
message = 'Missing required argument, filename.'
return [(None, None, None, message)]
try:
with open(os.path.expanduser(arg), encoding='utf-8') as f:
query = f.read()
except IOError as e:
return [(None, None, None, str(e))]
return self.sqlexecute.run(query)
def change_prompt_format(self, arg, **_):
"""
Change the prompt format.
"""
if not arg:
message = 'Missing required argument, format.'
return [(None, None, None, message)]
self.prompt_format = self.get_prompt(arg)
return [(None, None, None, "Changed prompt format to %s" % arg)]
def initialize_logging(self):
log_file = self.config['main']['log_file']
log_level = self.config['main']['log_level']
level_map = {'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG
}
handler = logging.FileHandler(os.path.expanduser(log_file))
formatter = logging.Formatter(
'%(asctime)s (%(process)d/%(threadName)s) '
'%(name)s %(levelname)s - %(message)s')
handler.setFormatter(formatter)
示例6: run_cli
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
def run_cli(self):
sqlexecute = self.sqlexecute
logger = self.logger
original_less_opts = self.adjust_less_opts()
self.initialize_completions()
completer = self.completer
def set_key_bindings(value):
if value not in ('emacs', 'vi'):
value = 'emacs'
self.key_bindings = value
project_root = os.path.dirname(PACKAGE_ROOT)
author_file = os.path.join(project_root, 'AUTHORS')
sponsor_file = os.path.join(project_root, 'SPONSORS')
key_binding_manager = mycli_bindings(get_key_bindings=lambda: self.key_bindings,
set_key_bindings=set_key_bindings)
print('Version:', __version__)
print('Chat: https://gitter.im/dbcli/mycli')
print('Mail: https://groups.google.com/forum/#!forum/mycli-users')
print('Home: http://mycli.net')
print('Thanks to the contributor -', thanks_picker([author_file, sponsor_file]))
def prompt_tokens(cli):
return [(Token.Prompt, self.get_prompt(self.prompt_format))]
get_toolbar_tokens = create_toolbar_tokens_func(lambda: self.key_bindings)
layout = create_default_layout(lexer=MyCliLexer,
reserve_space_for_menu=True,
get_prompt_tokens=prompt_tokens,
get_bottom_toolbar_tokens=get_toolbar_tokens,
extra_input_processors=[
ConditionalProcessor(
processor=HighlightMatchingBracketProcessor(chars='[](){}'),
filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()),
])
buf = CLIBuffer(always_multiline=self.multi_line, completer=completer,
history=FileHistory(os.path.expanduser('~/.mycli-history')),
complete_while_typing=Always())
application = Application(style=style_factory(self.syntax_style),
layout=layout, buffer=buf,
key_bindings_registry=key_binding_manager.registry,
on_exit=AbortAction.RAISE_EXCEPTION)
cli = CommandLineInterface(application=application, eventloop=create_eventloop())
try:
while True:
document = cli.run()
special.set_expanded_output(False)
# The reason we check here instead of inside the sqlexecute is
# because we want to raise the Exit exception which will be
# caught by the try/except block that wraps the
# sqlexecute.run() statement.
if quit_command(document.text):
raise EOFError
try:
document = self.handle_editor_command(cli, document)
except RuntimeError as e:
logger.error("sql: %r, error: %r", document.text, e)
logger.error("traceback: %r", traceback.format_exc())
self.output(str(e), err=True, fg='red')
continue
destroy = confirm_destructive_query(document.text)
if destroy is None:
pass # Query was not destructive. Nothing to do here.
elif destroy is True:
self.output('Your call!')
else:
self.output('Wise choice!')
continue
# 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)
if self.logfile:
self.logfile.write('\n# %s\n' % datetime.now())
self.logfile.write(document.text)
self.logfile.write('\n')
successful = False
start = time()
res = sqlexecute.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)
#.........这里部分代码省略.........
示例7: run
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
def run(self):
neo4j = Neo4j(self.host, self.port, self.username, self.password, self.ssl)
neo4j.connect()
self.neo4j = neo4j
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
if self.filename:
queries = self.filename.read()
queries = queries.split(";")[:-1]
for query in queries:
query += ";"
query = query.strip()
print("> " + query)
self.handle_query(query)
print()
return
click.secho(" ______ __ __ ______ __ __ ", fg="red")
click.secho("/\ ___\ /\ \_\ \ /\ ___\ /\ \ /\ \ ", fg="yellow")
click.secho("\ \ \____ \ \____ \ \ \ \____ \ \ \____ \ \ \ ", fg="green")
click.secho(" \ \_____\ \/\_____\ \ \_____\ \ \_____\ \ \_\ ", fg="blue")
click.secho(" \/_____/ \/_____/ \/_____/ \/_____/ \/_/ ", fg="magenta")
print("\nVersion: {}".format(__version__))
print("Bug reports: https://github.com/nicolewhite/cycli/issues\n")
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=FileHistory(filename=os.path.expanduser('~/.cycli_history')),
completer=completer,
complete_while_typing=Always()
)
application = Application(
style=CypherStyle,
buffer=buff,
layout=layout,
on_exit=AbortAction.RAISE_EXCEPTION,
key_bindings_registry=CypherBinder.registry
)
cli = CommandLineInterface(application=application, eventloop=create_eventloop())
try:
while True:
document = cli.run()
query = document.text
self.handle_query(query)
except Exception:
print("Goodbye!")
示例8: run_cli
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
def run_cli(self):
pgexecute = self.pgexecute
logger = self.logger
original_less_opts = self.adjust_less_opts()
completer = self.completer
self.refresh_completions()
def set_vi_mode(value):
self.vi_mode = value
key_binding_manager = pgcli_bindings(
get_vi_mode_enabled=lambda: self.vi_mode,
set_vi_mode_enabled=set_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')
def prompt_tokens(cli):
return [(Token.Prompt, '%s> ' % pgexecute.dbname)]
get_toolbar_tokens = create_toolbar_tokens_func(lambda: self.vi_mode)
layout = create_default_layout(lexer=PostgresLexer,
reserve_space_for_menu=True,
get_prompt_tokens=prompt_tokens,
get_bottom_toolbar_tokens=get_toolbar_tokens,
extra_input_processors=[
# Highlight matching brackets while editing.
ConditionalProcessor(
processor=HighlightMatchingBracketProcessor(chars='[](){}'),
filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()),
])
history_file = self.config['main']['history_file']
buf = PGBuffer(always_multiline=self.multi_line, completer=completer,
history=FileHistory(os.path.expanduser(history_file)),
complete_while_typing=Always())
application = Application(style=style_factory(self.syntax_style),
layout=layout, buffer=buf,
key_bindings_registry=key_binding_manager.registry,
on_exit=AbortAction.RAISE_EXCEPTION)
cli = CommandLineInterface(application=application,
eventloop=create_eventloop())
try:
while True:
document = cli.run()
# 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 EOFError
try:
document = self.handle_editor_command(cli, document)
except RuntimeError 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')
continue
# 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, self.pgspecial)
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
formatted = format_output(title, cur, headers, status,
self.table_format,
#.........这里部分代码省略.........
示例9: Saws
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
#.........这里部分代码省略.........
text = self.aws_cli.current_buffer.document.text
# If the user hit the F9 key, append 'docs' to the text
if from_fkey:
text = text.strip() + ' ' + AwsCommands.AWS_DOCS
tokens = text.split()
if len(tokens) > 2 and tokens[-1] == AwsCommands.AWS_DOCS:
prev_word = tokens[-2]
# If we have a command, build the url
if prev_word in self.commands:
prev_word = prev_word + '/'
url = base_url + prev_word + index_html
webbrowser.open(url)
return True
# if we have a command and subcommand, build the url
elif prev_word in self.sub_commands:
command_url = tokens[-3] + '/'
sub_command_url = tokens[-2] + '.html'
url = base_url + command_url + sub_command_url
webbrowser.open(url)
return True
webbrowser.open(base_url + index_html)
# If we still haven't opened the help doc at this point and the
# user hit the F9 key or typed docs, just open the main docs index
if from_fkey or AwsCommands.AWS_DOCS in tokens:
webbrowser.open(base_url + index_html)
return True
return False
def handle_cd(self, text):
"""Handles a `cd` shell command by calling python's os.chdir.
Simply passing in the `cd` command to subprocess.call doesn't work.
Note: Changing the directory within Saws will only be in effect while
running Saws. Exiting the program will return you to the directory
you were in prior to running Saws.
Attributes:
* text: A string representing the input command text.
Returns:
A boolean representing a `cd` command was found and handled.
"""
CD_CMD = 'cd'
stripped_text = text.strip()
if stripped_text.startswith(CD_CMD):
directory = ''
if stripped_text == CD_CMD:
# Treat `cd` as a change to the root directory.
# os.path.expanduser does this in a cross platform manner.
directory = os.path.expanduser('~')
else:
tokens = text.split(CD_CMD + ' ')
directory = tokens[-1]
try:
os.chdir(directory)
except OSError as e:
self.log_exception(e, traceback, echo=True)
return True
return False
def colorize_output(self, text):
"""Highlights output with pygments.
Only highlights the output if all of the following conditions are True:
* The color option is enabled
示例10: WharfeeCli
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
class WharfeeCli(object):
"""
The CLI implementation.
"""
dcli = None
keyword_completer = None
handler = None
saved_less_opts = None
config = None
config_template = 'wharfeerc'
config_name = '~/.wharfeerc'
def __init__(self, no_completion=False):
"""
Initialize class members.
Should read the config here at some point.
"""
self.config = self.read_configuration()
self.theme = self.config['main']['theme']
log_file = self.config['main']['log_file']
log_level = self.config['main']['log_level']
self.logger = create_logger(__name__, log_file, log_level)
# set_completer_options refreshes all by default
self.handler = DockerClient(
self.config['main'].as_int('client_timeout'),
self.clear,
self.refresh_completions_force,
self.logger)
self.completer = DockerCompleter(
long_option_names=self.get_long_options(),
fuzzy=self.get_fuzzy_match())
self.set_completer_options()
self.completer.set_enabled(not no_completion)
self.saved_less_opts = self.set_less_opts()
def read_configuration(self):
"""
:return:
"""
default_config = os.path.join(
self.get_package_path(), self.config_template)
write_default_config(default_config, self.config_name)
return read_config(self.config_name, default_config)
def get_package_path(self):
"""
Find out pakage root path.
:return: string: path
"""
from wharfee import __file__ as package_root
return os.path.dirname(package_root)
def set_less_opts(self):
"""
Set the "less" options and save the old settings.
What we're setting:
-F:
--quit-if-one-screen: Quit if entire file fits on first screen.
-R:
--raw-control-chars: Output "raw" control characters.
-X:
--no-init: Don't use termcap keypad init/deinit strings.
--no-keypad: Don't use termcap init/deinit strings.
This also disables launching "less" in an alternate screen.
:return: string with old options
"""
opts = os.environ.get('LESS', '')
os.environ['LESS'] = '-RXF'
return opts
def revert_less_opts(self):
"""
Restore the previous "less" options.
"""
os.environ['LESS'] = self.saved_less_opts
def write_config_file(self):
"""
Write config file on exit.
"""
self.config.write()
def clear(self):
"""
Clear the screen.
"""
click.clear()
def set_completer_options(self, cons=True, runs=True, imgs=True, vols=True):
"""
Set image and container names in Completer.
Re-read if needed after a command.
#.........这里部分代码省略.........
示例11: Haxor
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
#.........这里部分代码省略.........
use the standard @property and @attrib.setter for these attributes.
Lambdas cannot contain assignments so we're forced to define setters.
:rtype: :class:`prompt_toolkit.key_binding.manager
:return: KeyBindingManager with callables to set the toolbar options.
"""
def set_paginate_comments(paginate_comments):
"""Setter for paginating comments mode.
:type paginate: bool
:param paginate: The paginate comments mode.
"""
self.paginate_comments = paginate_comments
return KeyManager(
set_paginate_comments, lambda: self.paginate_comments)
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)
def _add_comment_pagination(self, document_text):
"""Add the command to enable comment pagination where applicable.
Pagination is enabled if the command views comments and the
browser flag is not enabled.
:type document_text: str
:param document_text: The input command.
:rtype: str
:return: the input command with pagination enabled.
"""
if not any(sub in document_text for sub in self.CMDS_NO_PAGINATE):
if any(sub in document_text for sub in self.CMDS_ENABLE_PAGINATE):
if platform.system() == 'Windows':
document_text += self.PAGINATE_CMD_WIN
else:
document_text += self.PAGINATE_CMD
return document_text
def handle_exit(self, document):
"""Exits if the user typed exit or quit
:type document: :class:`prompt_toolkit.document.Document`
:param document: An instance of `prompt_toolkit.document.Document`.
"""
if document.text in ('exit', 'quit'):
sys.exit()
def run_command(self, document):
"""Run the given command.
:type document: :class:`prompt_toolkit.document.Document`
:param document: An instance of `prompt_toolkit.document.Document`.
"""
try:
if self.paginate_comments:
document.text = self._add_comment_pagination(document.text)
subprocess.call(document.text, shell=True)
except Exception as e:
click.secho(e, fg='red')
def run_cli(self):
"""Run the main loop."""
click.echo('Version: ' + __version__)
click.echo('Syntax: hn <command> [params] [options]')
while True:
document = self.cli.run()
self.handle_exit(document)
self.run_command(document)
示例12: loop
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
def loop(cmd, history_file):
from prompt_toolkit import CommandLineInterface, AbortAction, Application
from prompt_toolkit.interface import AcceptAction
from prompt_toolkit.enums import DEFAULT_BUFFER
from prompt_toolkit.layout.processors import (
HighlightMatchingBracketProcessor,
ConditionalProcessor
)
from prompt_toolkit.key_binding.manager import KeyBindingManager
from prompt_toolkit.shortcuts import (create_default_layout,
create_default_output,
create_eventloop)
key_binding_manager = KeyBindingManager(
enable_search=True,
enable_abort_and_exit_bindings=True,
enable_vi_mode=Condition(lambda cli: _enable_vi_mode()))
layout = create_default_layout(
message=u'cr> ',
multiline=True,
lexer=SqlLexer,
extra_input_processors=[
ConditionalProcessor(
processor=HighlightMatchingBracketProcessor(chars='[](){}'),
filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
]
)
cli_buffer = CrashBuffer(
history=TruncatedFileHistory(history_file, max_length=MAX_HISTORY_LENGTH),
accept_action=AcceptAction.RETURN_DOCUMENT,
completer=SQLCompleter(cmd.connection, cmd.lines),
complete_while_typing=Always()
)
application = Application(
layout=layout,
style=CrateStyle,
buffer=cli_buffer,
key_bindings_registry=key_binding_manager.registry,
on_exit=AbortAction.RAISE_EXCEPTION,
on_abort=AbortAction.RETRY,
)
eventloop = create_eventloop()
output = create_default_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()
if doc:
cmd.process(doc.text)
except EOFError:
cmd.logger.warn(u'Bye!')
return
示例13: PGCli
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
class PGCli(object):
def __init__(self,
force_passwd_prompt=False,
never_passwd_prompt=False,
pgexecute=None,
pgclirc_file=None):
self.force_passwd_prompt = force_passwd_prompt
self.never_passwd_prompt = never_passwd_prompt
self.pgexecute = pgexecute
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(default_config, pgclirc_file)
self.pgspecial = PGSpecial()
# Load config.
c = self.config = load_config(pgclirc_file, default_config)
self.multi_line = c['main'].as_bool('multi_line')
self.vi_mode = c['main'].as_bool('vi')
self.pgspecial.timing_enabled = c['main'].as_bool('timing')
self.table_format = c['main']['table_format']
self.syntax_style = c['main']['syntax_style']
self.cli_style = c['colors']
self.wider_completion_menu = c['main'].as_bool('wider_completion_menu')
self.completion_refresher = CompletionRefresher()
self.logger = logging.getLogger(__name__)
self.initialize_logging()
self.query_history = []
# Initialize completer
smart_completion = c['main'].as_bool('smart_completion')
completer = PGCompleter(smart_completion, pgspecial=self.pgspecial)
self.completer = completer
self._completer_lock = threading.Lock()
self.register_special_commands()
self.cli = None
def register_special_commands(self):
self.pgspecial.register(
self.change_db,
'\\c',
'\\c[onnect] database_name',
'Change to a new database.',
aliases=('use', '\\connect', 'USE'))
self.pgspecial.register(
self.refresh_completions,
'\\#',
'\\#',
'Refresh auto-completions.',
arg_type=NO_QUERY)
self.pgspecial.register(
self.refresh_completions,
'\\refresh',
'\\refresh',
'Refresh auto-completions.',
arg_type=NO_QUERY)
self.pgspecial.register(self.execute_from_file, '\\i', '\\i filename',
'Execute commands from file.')
def change_db(self, pattern, **_):
if pattern:
db = pattern[1:-1] if pattern[0] == pattern[-1] == '"' else pattern
self.pgexecute.connect(database=db)
else:
self.pgexecute.connect()
yield (None, None, None, 'You are now connected to database "%s" as '
'user "%s"' % (self.pgexecute.dbname, self.pgexecute.user))
def execute_from_file(self, pattern, **_):
if not pattern:
message = '\\i: missing required argument'
return [(None, None, None, message)]
try:
with open(os.path.expanduser(pattern), encoding='utf-8') as f:
query = f.read()
except IOError as e:
return [(None, None, None, str(e))]
return self.pgexecute.run(query, self.pgspecial)
def initialize_logging(self):
log_file = self.config['main']['log_file']
log_level = self.config['main']['log_level']
level_map = {
'CRITICAL': logging.CRITICAL,
'ERROR': logging.ERROR,
'WARNING': logging.WARNING,
'INFO': logging.INFO,
'DEBUG': logging.DEBUG
#.........这里部分代码省略.........
示例14: MyCli
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
#.........这里部分代码省略.........
msg += "\n\t%s" % table_type
yield (None, None, None, msg)
else:
self.table_format = arg
yield (None, None, None, "Changed table Type to %s" % self.table_format)
def change_db(self, arg, **_):
if arg is None:
self.sqlexecute.connect()
else:
self.sqlexecute.connect(database=arg)
yield (
None,
None,
None,
'You are now connected to database "%s" as ' 'user "%s"' % (self.sqlexecute.dbname, self.sqlexecute.user),
)
def execute_from_file(self, arg, **_):
if not arg:
message = "Missing required argument, filename."
return [(None, None, None, message)]
try:
with open(os.path.expanduser(arg), encoding="utf-8") as f:
query = f.read()
except IOError as e:
return [(None, None, None, str(e))]
if self.destructive_warning and confirm_destructive_query(query) is False:
message = "Wise choice. Command execution stopped."
return [(None, None, None, message)]
return self.sqlexecute.run(query)
def change_prompt_format(self, arg, **_):
"""
Change the prompt format.
"""
if not arg:
message = "Missing required argument, format."
return [(None, None, None, message)]
self.prompt_format = self.get_prompt(arg)
return [(None, None, None, "Changed prompt format to %s" % arg)]
def initialize_logging(self):
log_file = self.config["main"]["log_file"]
log_level = self.config["main"]["log_level"]
level_map = {
"CRITICAL": logging.CRITICAL,
"ERROR": logging.ERROR,
"WARNING": logging.WARNING,
"INFO": logging.INFO,
"DEBUG": logging.DEBUG,
}
handler = logging.FileHandler(os.path.expanduser(log_file))
formatter = logging.Formatter(
"%(asctime)s (%(process)d/%(threadName)s) " "%(name)s %(levelname)s - %(message)s"
)
handler.setFormatter(formatter)
示例15: Saws
# 需要导入模块: from prompt_toolkit import CommandLineInterface [as 别名]
# 或者: from prompt_toolkit.CommandLineInterface import run [as 别名]
#.........这里部分代码省略.........
text = self.aws_cli.current_buffer.document.text
# If the user hit the F9 key, append 'docs' to the text
if from_fkey:
text = text.strip() + ' ' + AwsCommands.AWS_DOCS
tokens = text.split()
if len(tokens) > 2 and tokens[-1] == AwsCommands.AWS_DOCS:
prev_word = tokens[-2]
# If we have a command, build the url
if prev_word in self.commands:
prev_word = prev_word + '/'
url = base_url + prev_word + index_html
webbrowser.open(url)
return True
# if we have a command and subcommand, build the url
elif prev_word in self.sub_commands:
command_url = tokens[-3] + '/'
sub_command_url = tokens[-2] + '.html'
url = base_url + command_url + sub_command_url
webbrowser.open(url)
return True
webbrowser.open(base_url + index_html)
# If we still haven't opened the help doc at this point and the
# user hit the F9 key or typed docs, just open the main docs index
if from_fkey or AwsCommands.AWS_DOCS in tokens:
webbrowser.open(base_url + index_html)
return True
return False
def _handle_cd(self, text):
"""Handles a `cd` shell command by calling python's os.chdir.
Simply passing in the `cd` command to subprocess.call doesn't work.
Note: Changing the directory within Saws will only be in effect while
running Saws. Exiting the program will return you to the directory
you were in prior to running Saws.
Attributes:
* text: A string representing the input command text.
Returns:
A boolean representing a `cd` command was found and handled.
"""
CD_CMD = 'cd'
stripped_text = text.strip()
if stripped_text.startswith(CD_CMD):
directory = ''
if stripped_text == CD_CMD:
# Treat `cd` as a change to the root directory.
# os.path.expanduser does this in a cross platform manner.
directory = os.path.expanduser('~')
else:
tokens = text.split(CD_CMD + ' ')
directory = tokens[-1]
try:
os.chdir(directory)
except OSError as e:
self.log_exception(e, traceback, echo=True)
return True
return False
def _colorize_output(self, text):
"""Highlights output with pygments.
Only highlights the output if all of the following conditions are True:
* The color option is enabled