Python prompt_toolkit.PromptSession() Examples
The following are 27
code examples of prompt_toolkit.PromptSession().
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
, 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: common.py From questionary with MIT License | 6 votes |
def _fix_unecessary_blank_lines(ps: PromptSession) -> None: """This is a fix for additional empty lines added by prompt toolkit. This assumes the layout of the default session doesn't change, if it does, this needs an update.""" default_container = ps.layout.container default_buffer_window = ( default_container.get_children()[0].content.get_children()[1].content ) assert isinstance(default_buffer_window, Window) # this forces the main window to stay as small as possible, avoiding # empty lines in selections default_buffer_window.dont_extend_height = Always()
Example #3
Source File: wmdb.py From WitnessMe with GNU General Public License v3.0 | 6 votes |
def __init__(self, db_path): self.db_path = db_path self.completer = WMCompleter(self) self.signatures = Signatures() self.prompt_session = PromptSession( HTML("WMDB ≫ "), #bottom_toolbar=functools.partial(bottom_toolbar, ts=self.teamservers), completer=self.completer, complete_in_thread=True, complete_while_typing=True, auto_suggest=AutoSuggestFromHistory(), #rprompt=get_rprompt(False), #style=example_style, search_ignore_case=True )
Example #4
Source File: slow-history.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 6 votes |
def main(): print( "Asynchronous loading of history. Notice that the up-arrow will work " "for as far as the completions are loaded.\n" "Even when the input is accepted, loading will continue in the " "background and when the next prompt is displayed.\n" ) our_history = ThreadedHistory(SlowHistory()) # 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 #5
Source File: sqlite-cli.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 6 votes |
def main(database): connection = sqlite3.connect(database) session = PromptSession( lexer=PygmentsLexer(SqlLexer), completer=sql_completer, style=style ) while True: try: text = session.prompt("> ") except KeyboardInterrupt: continue # Control-C pressed. Try again. except EOFError: break # Control-D pressed. with connection: try: messages = connection.execute(text) except Exception as e: print(repr(e)) else: for message in messages: print(message) print("GoodBye!")
Example #6
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 #7
Source File: common.py From questionary with MIT License | 6 votes |
def create_inquirer_layout( ic: InquirerControl, get_prompt_tokens: Callable[[], List[Tuple[Text, Text]]], **kwargs ) -> Layout: """Create a layout combining question and inquirer selection.""" ps = PromptSession(get_prompt_tokens, reserve_space_for_menu=0, **kwargs) _fix_unecessary_blank_lines(ps) return Layout( HSplit( [ps.layout.container, ConditionalContainer(Window(ic), filter=~IsDone())] ) )
Example #8
Source File: util.py From coconut with Apache License 2.0 | 6 votes |
def prompt(self, msg): """Get input using prompt_toolkit.""" try: # prompt_toolkit v2 prompt = prompt_toolkit.PromptSession(history=self.history).prompt except AttributeError: # prompt_toolkit v1 prompt = partial(prompt_toolkit.prompt, history=self.history) return prompt( msg, multiline=self.multiline, vi_mode=self.vi_mode, wrap_lines=self.wrap_lines, enable_history_search=self.history_search, lexer=PygmentsLexer(CoconutLexer), style=style_from_pygments_cls( pygments.styles.get_style_by_name(self.style), ), )
Example #9
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 #10
Source File: CurseBreaker.py From CurseBreaker with GNU General Public License v3.0 | 5 votes |
def __init__(self): self.core = Core() self.session = PromptSession(reserve_space_for_menu=6) self.headless = False self.console = None self.table = None self.cfSlugs = None self.wowiSlugs = None self.completer = None self.os = platform.system() install()
Example #11
Source File: prompt.py From fuzzowski with GNU General Public License v2.0 | 5 votes |
def __init__(self) -> None: self.commands = self.get_commands() self.cmd_handler = CommandHandler(self.commands) self.completer = CommandCompleter(self.commands) self.style = self.get_style() self._break = False self.prompt_session = PromptSession(completer=self.completer, style=self.style, bottom_toolbar=self.bottom_toolbar, auto_suggest=AutoSuggestFromHistory()) super(CommandPrompt, self).__init__() # --------------------------------------------------------------- #
Example #12
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 #13
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 #14
Source File: base.py From hermit with Apache License 2.0 | 5 votes |
def __init__(self, signing_wallet: HDWallet, session: PromptSession = None) -> None: self.wallet = signing_wallet self.session = session self.signature: Optional[Dict] = None self.request_data: Optional[str] = None
Example #15
Source File: test_base.py From hermit with Apache License 2.0 | 5 votes |
def test_confirm_signature_prompt_in_session(self, mock_input, mock_display_qr_code, mock_request): mock_session = create_autospec(PromptSession) mock_session.prompt.return_value = 'y' mock_request.return_value = json.dumps(self.request) Signer(self.wallet, mock_session).sign(testnet=True) input_prompt = 'Sign the above transaction? [y/N] ' assert input_prompt in mock_session.prompt.call_args[0][0].value
Example #16
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 #17
Source File: up-arrow-partial-string-matching.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #18
Source File: auto-suggestion.py From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License | 5 votes |
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)
Example #19
Source File: prompt.py From Pytify with MIT License | 5 votes |
def custom_prompt(currentSong): session = PromptSession( message=get_prompt, history=history(), auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, bottom_toolbar=get_bottom_toolbar(currentSong), completer=completer(), complete_while_typing=True, complete_in_thread=True, style=style ) return session.prompt()
Example #20
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 #21
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 #22
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 #23
Source File: aiocmd.py From msldap with MIT License | 5 votes |
def run(self): if self._ignore_sigint and sys.platform != "win32": asyncio.get_event_loop().add_signal_handler(signal.SIGINT, self._sigint_handler) self.session = PromptSession(enable_history_search=True, key_bindings=self._get_bindings()) try: with patch_stdout(): await self._run_prompt_forever() finally: if self._ignore_sigint and sys.platform != "win32": asyncio.get_event_loop().remove_signal_handler(signal.SIGINT) self._on_close()
Example #24
Source File: shell.py From we-get with MIT License | 5 votes |
def shell(self, items, pargs): self.pargs = pargs self.items = items stdout.write( '\n') # When the fetching messege ends need to add \n after \r. self.prompt_show_items() history = InMemoryHistory() session = PromptSession() if PROMPT_TOOLKIT_V2 else None while True: kwargs = dict( history=history, auto_suggest=AutoSuggestFromHistory(), completer=WGCompleter(list(self.items.keys())), style=we_get_prompt_style ) try: p = prompt(u'we-get > ', **kwargs) except TypeError as e: log.debug('{}:{}'.format(type(e), e)) kwargs.pop('history') if PROMPT_TOOLKIT_V2: p = session.prompt(u'we-get > ', **kwargs) else: p = prompt(u'we-get > ', **kwargs) if self.prompt_no_command(p): continue elif self.prompt_is_single_command(p): command = p args = None else: _ = p.split() command = _[0] _.pop(0) args = ' '.join(_) if not self.prompt_verify_command(command, args): continue elif not self.prompt_parse_command(command, args): break
Example #25
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 #26
Source File: repl.py From hermit with Apache License 2.0 | 4 votes |
def repl(commands:Dict, mode="", help_command=None): commandCompleter = WordCompleter( [c for c in commands], sentence=True # allows hyphens ) oldSession = state.Session state.Session = PromptSession(key_bindings=Bindings, bottom_toolbar=bottom_toolbar, refresh_interval=0.1) state.Wallet.shards.interface.options = {'bottom_toolbar': bottom_toolbar} done = None with patch_stdout(): while not done: try: unlocked = ' ' if state.Wallet.unlocked(): unlocked = '*' command_line = state.Session.prompt(HTML('<b>{}{}></b> '.format(unlocked, mode)), completer=commandCompleter, ).split() if len(command_line) == 0: continue if command_line[0] in commands: command_fn = commands[command_line[0]] try: done = command_fn(*(command_line[1:])) except TypeError as err: if state.Debug: raise err if help_command is not None: help_command(command_line[0]) else: raise HermitError("Unknown command") except KeyboardInterrupt: continue except HermitError as e: print(e) if state.Debug: traceback.print_exc() continue except EOFError: break except Exception as err: print(err) if state.Debug: traceback.print_exc() break state.Session = oldSession
Example #27
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()