Python prompt_toolkit.history.FileHistory() Examples
The following are 27
code examples of prompt_toolkit.history.FileHistory().
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example.
You may also want to check out all available functions/classes of the module
prompt_toolkit.history
, or try the search function
.
Example #1
Source File: __main__.py From bibmanager with MIT License | 7 votes |
def cli_ads_search(args): """Command-line interface for ads-search call.""" if args.next: query = None else: completer = u.KeyWordCompleter(u.ads_keywords, bm.load()) session = prompt_toolkit.PromptSession( history=FileHistory(u.BM_HISTORY_ADS())) query = session.prompt( "(Press 'tab' for autocomplete)\n", auto_suggest=u.AutoSuggestCompleter(), completer=completer, complete_while_typing=False, ).strip() if query == "" and os.path.exists(u.BM_CACHE()): query = None elif query == "": return try: am.manager(query) except ValueError as e: print(f"\nError: {str(e)}")
Example #2
Source File: main.py From pgcli with BSD 3-Clause "New" or "Revised" License | 6 votes |
def refresh_completions(self, history=None, persist_priorities="all"): """ Refresh outdated completions :param history: A prompt_toolkit.history.FileHistory object. Used to load keyword and identifier preferences :param persist_priorities: 'all' or 'keywords' """ callback = functools.partial( self._on_completions_refreshed, persist_priorities=persist_priorities ) self.completion_refresher.refresh( self.pgexecute, self.pgspecial, callback, history=history, settings=self.settings, ) return [ (None, None, None, "Auto-completion refresh started in the background.") ]
Example #3
Source File: main.py From Slack-Gitsin with GNU General Public License v3.0 | 6 votes |
def main(): """ Start the Slack Client """ os.system("clear; figlet 'Slack Gitsin' | lolcat") history = FileHistory(os.path.expanduser("~/.slackHistory")) while True: text = prompt("slack> ", history=history, auto_suggest=AutoSuggestFromHistory(), on_abort=AbortAction.RETRY, style=DocumentStyle, completer=Completer(fuzzy_match=False, text_utils=TextUtils()), complete_while_typing=Always(), get_bottom_toolbar_tokens=get_bottom_toolbar_tokens, key_bindings_registry=manager.registry, accept_action=AcceptAction.RETURN_DOCUMENT ) slack = Slack(text) slack.run_command()
Example #4
Source File: main.py From kafka-shell with Apache License 2.0 | 6 votes |
def main(): settings = Settings() bindings = get_bindings(settings) executor = Executor(settings) toolbar = Toolbar(settings) completer = KafkaCompleter(settings) if settings.enable_auto_complete else None suggester = AutoSuggestFromHistory() if settings.enable_auto_suggest else None history = ThreadedHistory(FileHistory(get_user_history_path())) if settings.enable_history else InMemoryHistory() session = PromptSession(completer=completer, style=style, bottom_toolbar=toolbar.handler, key_bindings=bindings, history=history, include_default_pygments_style=False) while True: try: command = session.prompt([("class:operator", "> ")], auto_suggest=suggester) except KeyboardInterrupt: continue except EOFError: break else: executor.execute(command) settings.save_settings()
Example #5
Source File: prompt.py From aq with MIT License | 6 votes |
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()
Example #6
Source File: root.py From aioli with MIT License | 6 votes |
def open_shell(ctx): for idx, param in enumerate(ctx.parent.command.params): if param.name == "app_path": del ctx.parent.command.params[idx] for cmd in NON_SHELL_CMDS: del ctx.parent.command.commands[cmd] settings = dict( color_depth=config.PROMPT_COLOR_DEPTH, style=config.PROMPT_STYLE, history=FileHistory(".aioli.history"), message=[ ("class:prompt-name", f"[{ctx.obj.app_path}]"), ("class:prompt-marker", u"> "), ], # completer=ContextualCompleter() ) while True: try: if not repl(ctx, prompt_kwargs=settings): break except Exception as e: utils.echo(f"err> {str(e)}")
Example #7
Source File: __main__.py From azure-cli-shell with MIT License | 5 votes |
def main(args): os.environ[ENV_ADDITIONAL_USER_AGENT] = 'AZURECLISHELL/' + __version__ parser = argparse.ArgumentParser(prog='az-shell') parser.add_argument( '--style', dest='style', help='the colors of the shell', choices=get_options()) args = parser.parse_args(args) azure_folder = cli_config_dir() if not os.path.exists(azure_folder): os.makedirs(azure_folder) ACCOUNT.load(os.path.join(azure_folder, 'azureProfile.json')) CONFIG.load(os.path.join(azure_folder, 'az.json')) SESSION.load(os.path.join(azure_folder, 'az.sess'), max_age=3600) config = SHELL_CONFIGURATION shell_config_dir = azclishell.configuration.get_config_dir if args.style: given_style = args.style config.set_style(given_style) else: given_style = config.get_style() style = style_factory(given_style) if config.BOOLEAN_STATES[config.config.get('DEFAULT', 'firsttime')]: print("When in doubt, ask for 'help'") config.firsttime() shell_app = Shell( completer=AZCOMPLETER, lexer=AzLexer, history=FileHistory( os.path.join(shell_config_dir(), config.get_history())), app=APPLICATION, styles=style ) shell_app.run()
Example #8
Source File: console.py From python-sploitkit with GNU Affero General Public License v3.0 | 5 votes |
def __init__(self, parent=None, **kwargs): super(Console, self).__init__() # determine the relevant parent self.parent = parent if self.parent is not None and self.parent.level == self.level: while parent is not None and parent.level == self.level: parent = parent.parent # go up of one console level # raise an exception in the context of command's .run() execution, # to be propagated to console's .run() execution, setting the # directly higher level console in argument raise ConsoleDuplicate(self, parent) # back-reference the console self.config.console = self # configure the console regarding its parenthood if self.parent is None: if Console.parent is not None: raise Exception("Only one parent console can be used") Console.parent = self Console.parent._start_time = datetime.now() Console.appdispname = Console.appname Console.appname = Console.appname.lower() self.__init(**kwargs) else: self.parent.child = self # reset commands and other bound stuffs self.reset() # setup the session with the custom completer and validator completer, validator = CommandCompleter(), CommandValidator() completer.console = validator.console = self message, style = self.prompt hpath = Path(self.config.option("WORKSPACE").value).joinpath("history") self._session = PromptSession( message, completer=completer, history=FileHistory(hpath), validator=validator, style=Style.from_dict(style), ) CustomLayout(self)
Example #9
Source File: rlinit.py From mec with GNU General Public License v3.0 | 5 votes |
def prompt(session): ''' mec prompt ''' cmd_list = readline_init(session) # cook our completions completion_dict = dict.fromkeys(cmd_list) completion_dict["target"] = dict.fromkeys(os.listdir("./data")) completion_dict["set"] = dict.fromkeys(["auto-update", "proxy-pool"]) completion_dict["set"]["auto-update"] = dict.fromkeys(["True", "False"]) mec_completer = NestedCompleter.from_nested_dict(completion_dict) mec_ps = ANSI(colors.CYAN + colors.BOLD + "\nmec > " + colors.END) cmd_autosuggest = ThreadedAutoSuggest(MecAutoSuggest(completions=cmd_list)) try: mecprompt = PromptSession(message=mec_ps, mouse_support=True, history=FileHistory(HISTFILE), completer=mec_completer, complete_while_typing=True, reserve_space_for_menu=2, auto_suggest=cmd_autosuggest).prompt() except termios.error as err: colors.colored_print(f"[-] Fatal error: {err}", color_code=colors.RED) os.system("mec stop") return mecprompt
Example #10
Source File: app.py From aws-shell with Apache License 2.0 | 5 votes |
def __init__(self, completer, model_completer, docs, input=None, output=None, popen_cls=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 if popen_cls is None: popen_cls = subprocess.Popen self._popen_cls = popen_cls # 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()
Example #11
Source File: cli.py From synapse with Apache License 2.0 | 5 votes |
def prompt(self, text=None): ''' Prompt for user input from stdin. ''' if self.sess is None: hist = FileHistory(s_common.getSynPath('cmdr_history')) self.sess = PromptSession(history=hist) if text is None: text = self.cmdprompt with patch_stdout(): retn = await self.sess.prompt_async(text, vi_mode=self.vi_mode, enable_open_in_editor=True) return retn
Example #12
Source File: persistent-history.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
def main(): our_history = FileHistory(".example-history-file") # The history needs to be passed to the `PromptSession`. It can't be passed # to the `prompt` call because only one history can be used during a # session. session = PromptSession(history=our_history) while True: text = session.prompt("Say something: ") print("You said: %s" % text)
Example #13
Source File: kubeshell.py From kube-shell with Apache License 2.0 | 5 votes |
def __init__(self, refresh_resources=True): shell_dir = os.path.expanduser("~/.kube/shell/") self.history = FileHistory(os.path.join(shell_dir, "history")) if not os.path.exists(shell_dir): os.makedirs(shell_dir) self.toolbar = Toolbar(self.get_cluster_name, self.get_namespace, self.get_user, self.get_inline_help)
Example #14
Source File: maininterface.py From polymorph with GNU General Public License v2.0 | 5 votes |
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter(['capture', 'spoof', 'clear', 'import']) history = FileHistory(self._polym_path + '/.minterface_history') session = PromptSession(history=history) while True: try: command = session.prompt(HTML("<bold><red>PH</red> > </bold>"), completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in ["capture", "c"]: self._capture(command) elif command[0] in ["spoof", "s"]: self._spoof(command) elif command[0] in ["import", "i"]: self._import(command) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()
Example #15
Source File: tlistinterface.py From polymorph with GNU General Public License v2.0 | 5 votes |
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter(['show', 'dissect', 'template', 'wireshark', 'clear', 'back']) history = FileHistory(self._polym_path + '/.tlinterface_history') session = PromptSession(history=history) while True: try: command = session.prompt(HTML("<bold>PH:<red>cap</red> > </bold>"), completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in self.RET: break elif command[0] in ["show", "s"]: self._show(command) elif command[0] == "dissect": self._dissect(command) elif command[0] in ["template", "t"]: self._template(command) elif command[0] in ["wireshark", "w"]: self._wireshark(command) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()
Example #16
Source File: layerinterface.py From polymorph with GNU General Public License v2.0 | 5 votes |
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter(['show', 'name', 'field', 'fields', 'dump', 'recalculate', 'clear', 'back']) history = FileHistory(self._polym_path + '/.linterface_history') session = PromptSession(history=history) while True: try: command = session.prompt(HTML("<bold>PH:cap/t%d/<red>%s</red> > </bold>" % (self._tindex, self._l.name)), completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue # Argument parsing command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in self.RET: break elif command[0] in ["s", "show"]: self._show(command) elif command[0] == "name": self._name(command) elif command[0] in ["field", "f"]: self._field(command) elif command[0] in ["fields", "fs"]: self._fields(command) elif command[0] in ["dump", "d"]: self._dump(command) elif command[0] in ["recalculate", "r"]: self._recalculate(command) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()
Example #17
Source File: Exploiter.py From drupwn with GNU General Public License v3.0 | 5 votes |
def __init__(self, request, logger, config): self.request = request self.config = config self.logger = logger self.cmds = { "exploit": self._exploit, "check": self._check, "list": self._list, } self.auto_cmds = WordCompleter(["quit", "list", "check", "exploit"], ignore_case=True) self.history = FileHistory('.drupwn-history') self._load()
Example #18
Source File: history.py From Pytify with MIT License | 5 votes |
def history(): return FileHistory('%s/.pytify-search-history' % str(Path.home()))
Example #19
Source File: __init__.py From asn1tools with MIT License | 5 votes |
def _do_shell(_args): commands = ['compile', 'convert', 'help', 'exit'] completer = WordCompleter(commands, WORD=True) user_home = os.path.expanduser('~') history = FileHistory(os.path.join(user_home, '.asn1tools-history.txt')) session = PromptSession(completer=completer, complete_while_typing=True, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, history=history) input_spec = None output_spec = None output_codec = None print("\nWelcome to the asn1tools shell!\n") while True: try: line = session.prompt(u'$ ') except EOFError: return line = line.strip() if line: if line.startswith('compile'): input_spec, output_spec, output_codec = _handle_command_compile(line) elif line.startswith('convert'): _handle_command_convert(line, input_spec, output_spec, output_codec) elif line == 'help': _handle_command_help() elif line == 'exit': return else: print('{}: command not found'.format(line))
Example #20
Source File: main.py From cycli with MIT License | 4 votes |
def run(self): labels = self.neo4j.get_labels() relationship_types = self.neo4j.get_relationship_types() properties = self.neo4j.get_property_keys() if self.filename: with io.open(self.filename, "r") as f: queries = split_queries_on_semicolons(f.read()) for query in queries: 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("Cycli version: {}".format(__version__)) print("Neo4j version: {}".format(".".join(map(str, self.neo4j.neo4j_version)))) print("Bug reports: https://github.com/nicolewhite/cycli/issues\n") completer = CypherCompleter(labels, relationship_types, properties) layout = create_prompt_layout( lexer=CypherLexer, get_prompt_tokens=get_tokens, reserve_space_for_menu=8, ) buff = CypherBuffer( accept_action=AcceptAction.RETURN_DOCUMENT, history=FileHistory(filename=os.path.expanduser('~/.cycli_history')), completer=completer, complete_while_typing=True, ) application = Application( style=PygmentsStyle(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 UserWantsOut: print("Goodbye!") except Exception as e: print(e)
Example #21
Source File: fieldinterface.py From polymorph with GNU General Public License v2.0 | 4 votes |
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter(['value', 'type', 'show', 'name', 'slice', 'custom', 'size', 'dump', 'clear', 'back']) history = FileHistory(self._polym_path + '/.finterface_history') session = PromptSession(history=history) while True: try: command = session.prompt(HTML("<bold>PH:cap/t%d/%s/<red>%s</red> > </bold>" % (self._tindex, self._lname, self._f.name)), completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in self.RET: break elif command[0] in ['t', 'type']: self._type(command) elif command[0] in ['v', 'value']: self._value(command) elif command[0] in ['s', 'show']: self._show(command) elif command[0] == 'name': self._name(command) elif command[0] == "slice": print(self._f.slice, '\n') elif command[0] == "custom": self._custom(command) elif command[0] == "size": print(self._f.size, '\n') elif command[0] in ['d', 'dump']: Interface.color_dump(self._f.raw, self._f.slice.start, self._f.slice.stop) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()
Example #22
Source File: templateinterface.py From polymorph with GNU General Public License v2.0 | 4 votes |
def run(self): """Runs the interface and waits for user input commands.""" completer = WordCompleter(['show', 'name', 'layer', 'dump', 'layers', 'preconditions', 'postconditions', 'executions', 'intercept', 'timestamp', 'version', 'save', 'description', 'spoof', 'clear', 'back']) # Initialization of the command history history = FileHistory(join(self._polym_path, '.tinterface_history')) session = PromptSession(history=history) while True: try: command = session.prompt(HTML("<bold>PH:cap/<red>t%d</red> > </bold>" % self._index), completer=completer, complete_style=CompleteStyle.READLINE_LIKE, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True) except KeyboardInterrupt: self.exit_program() continue command = command.split(" ") if command[0] in self.EXIT: self.exit_program() elif command[0] in self.RET: break elif command[0] == "name": self._name(command) elif command[0] in ["dump", "d"]: self._dump(command) elif command[0] in ["layer", "l"]: self._layer(command) elif command[0] in ['precs', 'preconditions']: self._conditions(command, 'preconditions') elif command[0] in ['posts', 'postconditions']: self._conditions(command, 'postconditions') elif command[0] in ['execs', 'executions']: self._conditions(command, 'executions') elif command[0] in ["show", "s"]: self._show(command) elif command[0] in ["intercept", "i"]: self._intercept(command) elif command[0] in ["layers", "ls"]: self._layers(command) elif command[0] == "timestamp": print(self._t.timestamp, '\n') elif command[0] == "version": self._version(command) elif command[0] in ['desc', 'description']: self._description(command) elif command[0] == "save": self._save(command) elif command[0] in ["spoof"]: self._spoof(command) elif command[0] == "clear": Interface._clear() elif command[0] == "": continue else: Interface._wrong_command()
Example #23
Source File: rtxmlrpc.py From pyrocore with GNU General Public License v2.0 | 4 votes |
def do_repl(self): """REPL for rTorrent XMLRPC commands.""" from prompt_toolkit import prompt from prompt_toolkit.history import FileHistory from prompt_toolkit.auto_suggest import AutoSuggestFromHistory from prompt_toolkit.contrib.completers import WordCompleter self.options.quiet = False proxy = self.open() ps1 = proxy.session.name() + u'> ' words = ['help', 'stats', 'exit'] words += [x + '=' for x in proxy.system.listMethods()] history_file = os.path.join(config.config_dir, '.rtxmlrpc_history') while True: try: try: cmd = prompt(ps1, completer=WordCompleter(words), auto_suggest=AutoSuggestFromHistory(), history=FileHistory(history_file)) except KeyboardInterrupt: cmd = '' if not cmd: print("Enter '?' or 'help' for usage information, 'Ctrl-D' to exit.") if cmd in {'?', 'help'}: self.repl_usage() continue elif cmd in {'', 'stats'}: print(repr(proxy).split(None, 1)[1]) continue elif cmd in {'exit'}: raise EOFError() try: method, raw_args = cmd.split('=', 1) except ValueError: print("ERROR: '=' not found") continue raw_args = raw_args.split(',') args = self.cooked(raw_args) self.execute(proxy, method, args) except EOFError: print('Bye from {!r}'.format(proxy)) break
Example #24
Source File: shell.py From vexbot with GNU General Public License v3.0 | 4 votes |
def __init__(self, history_filepath=None): self._logger = logging.getLogger(__name__) if history_filepath is None: self._logger.info(' getting default history filepath.') history_filepath = _get_default_history_filepath() self._logger.info(' history filepath %s', history_filepath) self.history = FileHistory(history_filepath) self.messaging = _Messaging('shell', run_control_loop=True) # TODO: Cleanup this API access self.messaging._heartbeat_reciever.identity_callback = self._identity_callback self._thread = _Thread(target=self.messaging.start, daemon=True) self._bot_status_monitor = PeriodicCallback(self._monitor_bot_state, 1000) self.shebangs = ['!', ] self.command_observer = CommandObserver(self.messaging, prompt=self) commands = self.command_observer._get_commands() self._word_completer = WordCompleter(commands, WORD=_WORD) self._services_completer = ServiceCompleter(self._word_completer) self.author_interface = AuthorInterface(self._word_completer, self.messaging) self.service_interface = ServiceInterface(self._word_completer, self.messaging) self.entity_interface = EntityInterface(self.author_interface, self.service_interface) self._bot_status = '' super().__init__(message='vexbot: ', history=self.history, completer=self._services_completer, enable_system_prompt=True, enable_suspend=True, enable_open_in_editor=True, complete_while_typing=False) self.print_observer = PrintObserver(self.app) self._print_subscription = self.messaging.chatter.subscribe(self.print_observer) self.messaging.chatter.subscribe(LogObserver()) self.messaging.command.subscribe(self.command_observer) self.messaging.command.subscribe(ServicesObserver(self._identity_setter, self._set_service_completion))
Example #25
Source File: __init__.py From edgedb with Apache License 2.0 | 4 votes |
def build_propmpt(self) -> pt_shortcuts.PromptSession: history = pt_history.FileHistory( os.path.expanduser('~/.edgedbhistory')) bindings = pt_key_binding.KeyBindings() handle = bindings.add @handle('f3') # type: ignore def _mode_toggle(event: Any) -> None: self.context.toggle_query_mode() @handle('f4') # type: ignore def _implicit_toggle(event: Any) -> None: self.context.toggle_implicit() @handle('f5') # type: ignore def _introspect_toggle(event: Any) -> None: self.context.toggle_introspect_types() if self.context.introspect_types: self.ensure_connection() self.introspect_db(self.connection) else: self.context.typenames = None @handle('tab') # type: ignore def _tab(event: Any) -> None: b = prompt.app.current_buffer before_cursor = b.document.current_line_before_cursor if b.text and (not before_cursor or before_cursor.isspace()): b.insert_text(' ') prompt = pt_shortcuts.PromptSession( lexer=pt_lexers.PygmentsLexer(eql_pygments.EdgeQLLexer), include_default_pygments_style=False, completer=pt_complete.DummyCompleter(), reserve_space_for_menu=6, message=self.get_prompt_tokens, prompt_continuation=self.get_continuation_tokens, bottom_toolbar=self.get_toolbar_tokens, multiline=is_multiline, history=history, complete_while_typing=pt_filters.Always(), key_bindings=bindings, style=self.style, editing_mode=pt_enums.EditingMode.VI, search_ignore_case=True, ) return prompt
Example #26
Source File: console.py From gsheets-db-api with MIT License | 4 votes |
def main(): history = FileHistory(os.path.expanduser('~/.gsheetsdb_history')) arguments = docopt(__doc__, version=__version__.__version__) auth = { 'service_account_file': arguments['--service-account-file'], 'subject': arguments['--subject'], } credentials = get_credentials_from_auth(**auth) connection = connect(credentials) headers = int(arguments['--headers']) cursor = connection.cursor() lexer = PygmentsLexer(SqlLexer) words = keywords + aggregate_functions + scalar_functions completer = WordCompleter(words, ignore_case=True) style = style_from_pygments_cls(get_style_by_name('manni')) while True: try: query = prompt( 'sql> ', lexer=lexer, completer=completer, style=style, history=history) except (EOFError, KeyboardInterrupt): break # Control-D pressed. # run query query = query.strip('; ').replace('%', '%%') if query: try: result = cursor.execute(query, headers=headers) except Exception as e: if arguments['--raise']: raise print(e) continue columns = [t[0] for t in cursor.description or []] print(tabulate(result, headers=columns)) print('See ya!')
Example #27
Source File: main.py From pgcli with BSD 3-Clause "New" or "Revised" License | 4 votes |
def run_cli(self): logger = self.logger history_file = self.config["main"]["history_file"] if history_file == "default": history_file = config_location() + "history" history = FileHistory(os.path.expanduser(history_file)) self.refresh_completions(history=history, persist_priorities="none") self.prompt_app = self._build_cli(history) if not self.less_chatty: print("Server: PostgreSQL", self.pgexecute.server_version) print("Version:", __version__) print("Chat: https://gitter.im/dbcli/pgcli") print("Home: http://pgcli.com") try: while True: try: text = self.prompt_app.prompt() except KeyboardInterrupt: continue try: text = self.handle_editor_command(text) except RuntimeError as e: logger.error("sql: %r, error: %r", text, e) logger.error("traceback: %r", traceback.format_exc()) click.secho(str(e), err=True, fg="red") continue # Initialize default metaquery in case execution fails self.watch_command, timing = special.get_watch_command(text) if self.watch_command: while self.watch_command: try: query = self.execute_command(self.watch_command) click.echo( "Waiting for {0} seconds before repeating".format( timing ) ) sleep(timing) except KeyboardInterrupt: self.watch_command = None else: query = self.execute_command(text) self.now = dt.datetime.today() # Allow PGCompleter to learn user's preferred keywords, etc. with self._completer_lock: self.completer.extend_query_history(text) self.query_history.append(query) except (PgCliQuitError, EOFError): if not self.less_chatty: print("Goodbye!")