def new(*args, **kwargs): project_name = kwargs["project_name"] description = click.prompt("description") author_name = click.prompt("author_name") author_email = click.prompt("author_email") license_completer = FuzzyWordCompleter(licenses) license = prompt( "Select license: ", completer=license_completer, complete_while_typing=True, ) classifier_completer = FuzzyWordCompleter(classifiers) classifier = prompt( "Select classifier: ", completer=classifier_completer, complete_while_typing=True, ) metadata = { "name": project_name, "description": description, "author_name": author_name, "author_email": author_email, "license": license, "classifiers": classifier, } print() pprint(metadata)
def interact(connection): write = connection.send # When a client is connected, erase the screen from the client and say # Hello. clear() write('Welcome to our chat application!\n') write('All connected clients will receive what you say.\n') name = yield From(prompt(message='Type your name: ', async_=True)) # Random color. color = random.choice(COLORS) _connection_to_color[connection] = color # Send 'connected' message. _send_to_everyone(connection, name, '(connected)', color) # Prompt. prompt_msg = HTML('<reverse fg="{}">[{}]</reverse> > ').format( color, name) _connections.append(connection) try: # Set Application. while True: try: result = yield From(prompt(message=prompt_msg, async_=True)) _send_to_everyone(connection, name, result, color) except KeyboardInterrupt: pass except EOFError: _send_to_everyone(connection, name, '(leaving)', color) finally: _connections.remove(connection)
def __call__(self): if hasattr(signal, 'SIGHUP'): signal.signal(signal.SIGHUP, partial(self.exit, self)) elif hasattr(signal, 'SIGTERM'): # On windows listen to SIGTERM because SIGHUP is not available signal.signal(signal.SIGTERM, partial(self.exit, self)) try: print( 'WARN: Receiving and pushing events might cover over the console ' + 'interface. Press Ctrl + V or call command "verbose" to turn this ' + 'behaviour on or off. \n') if self.cl_args.verbose: prompt('Press enter to continue...') # starts network client in a new thread network_utils.start_reactor_thread() # listen to hashgraph actions network_utils.start_listening(self.network, self.cl_args.ip, self.cl_args.port, self.cl_args.dirty) self.network.start_push_thread() if self.cl_args.bootstrap_push: ip, port = self.cl_args.bootstrap_push.split(':') thread = BootstrapPushThread(ip, port, self.network) thread.daemon = True thread.start() super().__call__() # Ctrl+C throws KeyBoardInterruptException, Ctrl+D throws EOFException finally: self.exit()
def set_parameter(pck_name): event = select_event() seed = prompt('请输入种子数(1-10000):') throttle_time = prompt('请输入事件间隔时间(ms):') count = prompt('请输入事件运行次数:') monkey_cmd = 'monkey -p {pck_name} {event} -s {seed} --throttle {throttle_time} --ignore-timeouts ' \ '--ignore-crashes --monitor-native-crashes -v -v -v {count} >'.format(pck_name=pck_name, event=event, seed=seed, throttle_time=throttle_time, count=count) print_color( 'warning', '\n您设置的命令参数如下(大约执行%s秒):\n\n%s\n' % (str(round( (float(throttle_time) / 1000) * int(count) / 3, 1)), monkey_cmd), end='\n') cf2 = configparser.ConfigParser() cf2.set('DEFAULT', 'cmd', value=monkey_cmd) cf2.set('DEFAULT', 'package_name', value=pck_name) cf2.set('DEFAULT', 'net', value='wifi') fp = open('monkey.ini', 'w+') cf2.write(fp) fp.close() prompt('按回车开始测试,Ctrl+C结束测试!')
def acknowledge(*args, no_user_input: bool = False, **kwargs) -> None: echo(*args, **kwargs) if no_user_input: return shortcuts.prompt("", **kwargs) echo("")
def interact(connection): write = connection.send # When a client is connected, erase the screen from the client and say # Hello. clear() write('Welcome to our chat application!\n') write('All connected clients will receive what you say.\n') name = yield From(prompt(message='Type your name: ', async_=True)) # Random color. color = random.choice(COLORS) _connection_to_color[connection] = color # Send 'connected' message. _send_to_everyone(connection, name, '(connected)', color) # Prompt. prompt_msg = HTML('<reverse fg="{}">[{}]</reverse> > ').format(color, name) _connections.append(connection) try: # Set Application. while True: try: result = yield From(prompt(message=prompt_msg, async_=True)) _send_to_everyone(connection, name, result, color) except KeyboardInterrupt: pass except EOFError: _send_to_everyone(connection, name, '(leaving)', color) finally: _connections.remove(connection)
def attck_prompt(): #session = PromptSession() ==> from prompt_toolkit import PromptSession while True: try: selected_mode = prompt(message, completer=options_suggester, style=style, validator=Selection_Validator(options)) message_section = [ ('class:attck', 'ATT&CK'), ('class:section', f' [{selected_mode}]'), ('class:gt', ' > '), ] except KeyboardInterrupt: break while True: try: if selected_mode == 'search_mode': selection = prompt( message_section, completer=techinques_suggester, style=style, validator=Selection_Validator(techinques)) if selection == 'quit': exit() else: selected_technique_data = techinques_data[selection] print_title('\nTechnique: ', selection, end='\n') print_title('\nID: ', selected_technique_data[0], end='\n') print_title('\nDescription:\n', selected_technique_data[1], end='\n\n') else: selection = prompt(message_section, style=style) if selection == 'quit': print('Bye') exit() else: random_selection = random.choice(techinques) selected_technique_data = techinques_data[ random_selection] print_title('\nTechnique: ', random_selection, end='\n') print_title('\nID: ', selected_technique_data[0], end='\n') print_title('\nDescription:\n', selected_technique_data[1], end='\n\n') except KeyboardInterrupt: print(f'{BLUE}{BOLD}[!]{ENDC} {BOLD}Exiting {selected_mode}', end='\n\n') break print('Bye')
def createAVD(): image = prompt( "🏁 Please enter the SDK image name (type system for suggestions): ", completer=SDKCompleter()) name = prompt("👉 Enter the name of your virtual device: ") os.system("echo 'no' | avdmanager create avd -n {} -k '{}'".format( name, image)) print("\n✅ Your AVD has been created!")
def add_entidad(c): """Añade entidad creadora""" # RF-2.1. Añadir entidad creadora. Esta función registra una # entidad creadora dentro del sistema a partir de su nombre y # tipo. print('Añadiendo una entidad creadora.') ent_nombre = prompt("Nombre: ") ent_tipo = prompt("Tipo: ") c.execute('INSERT INTO entidadCreadora VALUES (?, ?)', (ent_nombre, ent_tipo))
def _get_user_input(self): """ Display appropriate label and collect user input. This private method displays the appropriate prompt label for the field using the appropriate display function and collect the user input. Returns ------- user_input : list or str A string for fields that accepts a single input or a list of strings for fields that accept multiple inputs, e.g., subgroups. """ # if we are dealing with a field that accepts multiple inputs if self.count == 'multiple': # instantiate a blank list to hold the multiple values values = [] # show the name of the field as a heading but do not # ask for input yet print_formatted_text(HTML(f" <b>{self.label}</b>")) # ask the user how many of the multiple inputs they # intend to provide; this must be non-zero num_entries = prompt(" How many do you want to specify: ", validator=self._make_integer_validator()) num_entries = int(num_entries) # display secondary prompts, one for each of the inputs # with the appropriate completer, validator, and style for i in range(num_entries): value = prompt(f" Enter #{i+1}: ", completer=self.completer, validator=self.validator, complete_style=self.complete_style) # save the value in the list values.append(value) # this is what we will return user_input = values # if we are dealing with a simple single-input field else: # nothing fancy, just display the label, attach # the appropriate completer, validator, and style, # and get the user input user_input = prompt(HTML(f" <b>{self.label}</b>: "), completer=self.completer, validator=self.validator, complete_style=self.complete_style) return user_input
def add_genero(c): """Añade un género""" # RF-2.4. Añadir un género # Esta función registra un género en el sistema a partir de un nombre, # un identificador, y, opcionalmente, un supergénero al que pertenece # como subgénero. gen_nombre = prompt("Nombre del género: ") gen_id = prompt("Identificador de género: ") gen_supg = leer2(c, "generoSupergenero", "identificador", "Supergénero: ") c.execute('INSERT INTO generoSupergenero VALUES (?, ?, ?)', (gen_id, gen_nombre, gen_supg))
def get_input(self, ctx): self.empty_line() if ctx: completer = WordCompleter(ctx.known_words, ignore_case=True) s = prompt(get_prompt_tokens=_get_prompt_tokens, get_bottom_toolbar_tokens=_get_toolbar(ctx), completer=completer, style=_style, history=_history).strip() else: s = prompt(get_prompt_tokens=_get_prompt_tokens, get_bottom_toolbar_tokens=_get_toolbar(ctx), style=_style).strip() if len(s) > 0: return s return self.get_input(ctx)
def main(): # Simple completion menu. print('(The completion menu displays colors.)') prompt('Type a color: ', completer=ColorCompleter()) # Multi-column menu. prompt('Type a color: ', completer=ColorCompleter(), complete_style=CompleteStyle.MULTI_COLUMN) # Readline-like prompt('Type a color: ', completer=ColorCompleter(), complete_style=CompleteStyle.READLINE_LIKE) # Prompt with true color output. message = [('#cc2244', 'T'), ('#bb4444', 'r'), ('#996644', 'u'), ('#cc8844', 'e '), ('#ccaa44', 'C'), ('#bbaa44', 'o'), ('#99aa44', 'l'), ('#778844', 'o'), ('#55aa44', 'r '), ('#33aa44', 'p'), ('#11aa44', 'r'), ('#11aa66', 'o'), ('#11aa88', 'm'), ('#11aaaa', 'p'), ('#11aacc', 't'), ('#11aaee', ': ')] prompt(message, completer=ColorCompleter(), color_depth=ColorDepth.TRUE_COLOR)
def cmdloop(self, intro=None): """Enters a loop that reads and execute input from user.""" if intro: print(intro) _auto_suggest = AutoSuggestFromHistory() while not builtins.__xonsh_exit__: try: token_func, style_cls = self._get_prompt_tokens_and_style() mouse_support = builtins.__xonsh_env__.get('MOUSE_SUPPORT') if builtins.__xonsh_env__.get('AUTO_SUGGEST'): auto_suggest = _auto_suggest else: auto_suggest = None completions_display = builtins.__xonsh_env__.get('COMPLETIONS_DISPLAY') multicolumn = (completions_display == 'multi') completer = None if completions_display == 'none' else self.pt_completer line = prompt( mouse_support=mouse_support, auto_suggest=auto_suggest, get_prompt_tokens=token_func, style=style_cls, completer=completer, history=self.history, key_bindings_registry=self.key_bindings_manager.registry, display_completions_in_columns=False) if not line: self.emptyline() else: line = self.precmd(line) self.default(line) except KeyboardInterrupt: self.reset_buffer() except EOFError: break
def main(): cmd_index = 0 args = parse_args() with ExtendedKazooClient(hosts=args.zk_url, timeout=2) as zkcli: cmdrunner = ZKCommandRunner(zkcli) while True: # We need a new completer for each command completer = ZkCompleter(zkcli) try: cmd = prompt('(%d) > ' % (cmd_index), history=history, auto_suggest=auto_suggest, completer=completer, lexer=ZkCliLexer, style=MonokaiStyle) try: out = cmdrunner.run(cmd) except Exception as exc: print(exc) else: if out is not None: print(out) except (KeyboardInterrupt, EOFError) as exc: break except Exception: traceback.print_exc() finally: cmd_index += 1
def run(self): print(self.startinfo) if self.history_file == '': history = InMemoryHistory() else: history = FileHistory(os.path.expanduser(self.history_file)) completer = MatchCompleter(self.get_candidate) while True: try: text = prompt( get_prompt_tokens=self.get_prompt_tokens, completer=completer, history=history, auto_suggest=AutoSuggestFromHistory(), get_bottom_toolbar_tokens=self.get_bottom_toolbar_tokens, patch_stdout=True, mouse_support=True, true_color=True, style=self.style) msg = self._handler(text) if msg: print(msg) except KeyboardInterrupt: print('KeyboardInterrupt') continue except EOFError: break print(self.exitinfo)
def __prompt_for_account(account_names): print("{}#--------------------------------------------------#".format( Colors.lblue)) print("# {}To which account would you like to login?{} #".format( Colors.white, Colors.lblue)) print("# {}Start typing an account name or{} #".format( Colors.white, Colors.lblue)) print('# {}"list" to list accounts{} #'.format( Colors.white, Colors.lblue)) print("#--------------------------------------------------#{}".format( Colors.normal)) account_names.append("list") def is_valid(account): return account in account_names account_completer = FuzzyWordCompleter(account_names, WORD=True) validator = Validator.from_callable(is_valid, error_message="Not a valid account", move_cursor_to_end=True) while True: account = prompt( "Account: ", completer=account_completer, complete_while_typing=True, validator=validator, ) if account == "list": for account_name in account_names: if account_name != "list": print("\t{}{}{}".format(Colors.yellow, account_name, Colors.normal)) else: return account
def select_nav_strategy(self): nav_names = [n.__name__ for n in self.NAVIGATION_STRATEGIES] print("Choose a navigation strategy: ") for idx, obj in enumerate(nav_names): print('[{}] - {}'.format(str(idx + 1), obj)) ans = prompt('> ') self.choosen_nav_strategy = self.NAVIGATION_STRATEGIES[int(ans) - 1]
def start(self): """ main start function, here we handle the command get loop and unicorn istance creation :return: """ if not self.emu_instance: self.initialize() utils.clear_terminal() print(utils.get_banner()) print('\n\n\t' + utils.white_bold('Contribute ') + 'https://github.com/iGio90/uDdbg\n') print('\t' + 'Type ' + utils.white_bold_underline('help') + ' to begin.\n') main_apix = colored(MENU_APPENDIX + " ", 'red', attrs=['bold', 'dark']) print() while True: print(main_apix, end='', flush=True) text = prompt('', history=self.history, auto_suggest=AutoSuggestFromHistory()) # only grant the use of empty command to replicate the last command while in cli. No executors if len(text) == 0 and self.last_command is not None: self.functions_instance.parse_command(self.last_command) continue self.last_command = text # send command to the parser self.functions_instance.parse_command(text)
def question(message, **kwargs): default = kwargs.pop('default', '') validate_prompt = kwargs.pop('validate', None) if validate_prompt: if inspect.isclass(validate_prompt) and issubclass( validate_prompt, Validator): kwargs['validator'] = validate_prompt() elif callable(validate_prompt): class _InputValidator(Validator): def validate(self, document): verdict = validate_prompt(document.text) if not verdict == True: if verdict == False: verdict = 'invalid input' raise ValidationError(message=verdict, cursor_position=len( document.text)) kwargs['validator'] = _InputValidator() # TODO style defaults on detail level kwargs['style'] = kwargs.pop('style', default_style) qmark = kwargs.pop('qmark', '?') def _get_prompt_tokens(): return [('class:questionmark', qmark), ('class:question', ' %s ' % message)] return prompt(message=_get_prompt_tokens, lexer=SimpleLexer('class:answer'), default=default, **kwargs)
def cmdloop(self, intro=None): """Enters a loop that reads and execute input from user.""" if intro: print(intro) _auto_suggest = AutoSuggestFromHistory() while not builtins.__xonsh_exit__: try: token_func, style_cls = self._get_prompt_tokens_and_style() mouse_support = builtins.__xonsh_env__.get('MOUSE_SUPPORT') if builtins.__xonsh_env__.get('AUTO_SUGGEST'): auto_suggest = _auto_suggest else: auto_suggest = None completions_display = builtins.__xonsh_env__.get( 'COMPLETIONS_DISPLAY') multicolumn = (completions_display == 'multi') completer = None if completions_display == 'none' else self.pt_completer line = prompt( mouse_support=mouse_support, auto_suggest=auto_suggest, get_prompt_tokens=token_func, style=style_cls, completer=completer, history=self.history, key_bindings_registry=self.key_bindings_manager.registry, display_completions_in_columns=False) if not line: self.emptyline() else: line = self.precmd(line) self.default(line) except KeyboardInterrupt: self.reset_buffer() except EOFError: break
def resolve_mnemonic_conflict(matching_filenames: List[GoogleDriveFile]) -> GoogleDriveFile: """ A function to ask the user to resolve any mnemonic conflicts that can arise because of how Google Drive works. Since Google Drive has display names that are not unique and since we want to use traditional file pathing as much as possible it is possible that a filename may correspond to many different files. In that case we need to ask the user which one they meant to reference with their query Parameters: matching_filenames (List[GoogleDriveFile]): A list of all google drive files matched the query by the user Returns: file_ids[response] (GoogleDriveFile): The GoogleDriveFile whose ID was entered by the user when prompted """ # Cache a dictionary linking all file ids to their corresponding file objects file_ids = {file['id']: file for file in matching_filenames} while 1: # Let the user know what is going wrong before anything else print_formatted_text(ANSI("\x1b[31mThere are multiple files with the same filename given!\n")) # Until the user provides the info we want keep printing the matching files for file in matching_filenames: pretty_date = file['modifiedDate'][:file['modifiedDate'].index('.')].replace('T', ' ') print_formatted_text(ANSI(f"\x1b[36mDisplay Name: \x1b[37m{file['title']} \x1b[36mLast Modified: " f"\x1b[37m{pretty_date} \x1b[36mFile ID: \x1b[37m{file['id']}")) # Newline for terminal readability and prompt the user to resolve the conflict print_formatted_text("") response = prompt(ANSI('\x1b[31mPlease copy/paste the ID of the file to which you were referring: ')) # If the user's response is a valid key then return the associated file if response in file_ids.keys(): return file_ids[response]
def resolve_file_conversion(remote_file: GoogleDriveFile) -> str: """ A function to take in a remote file and return to the caller a string that represents the file extension to use for this file. This exists to let users who may not know what conversion are available see all options that are available to them given a document type so they can download the file as the one best suited to their needs. Parameters: remote_file (GoogleDriveFile): The remote file who we are attempting to get the conversion for Returns: conversion_opts[user_input] (str): The file extension we are converting this file to """ while 1: # Print the helpful prompt on what the user is choosing and cache the supported conversions list for this # file print_formatted_text(ANSI(f"\x1b[36mWhat file type would you like to convert \"{remote_file['title']}\" to?")) conversion_opts = [ext for ext, link in SUPPORTED_FILE_TYPES.items() if link in remote_file['exportLinks']] # Print out all of the possible conversion's for this document and their associated number for choice, conversion in enumerate(conversion_opts): print_formatted_text(f"[{choice + 1}]: {conversion}") try: # Prompt the user for their choice of the file types printed out above user_input = int(prompt(ANSI(f'\x1b[36mChoose [1-{len(conversion_opts)}]: '))) - 1 # If the user input a valid index then return the conversion extension they desire if 0 <= user_input < len(conversion_opts): return conversion_opts[user_input] # If the user input a non integer cast-able value then inform them to use the numbers except ValueError: print_formatted_text(ANSI('\x1b[31mPlease input the integer that corresponds to your desired file type'))
def main(): text = prompt( "Give some animals: ", completer=animal_completer, complete_style=CompleteStyle.MULTI_COLUMN, ) print("You said: %s" % text)
def modbus_prompt(client, args): history = InMemoryHistory() completer = WordCompleter(['read', 'write', 'id', 'diag'], ignore_case=True) while True: text = prompt('modbus> ', completer=completer, history=history) command = text.lower().split() if command[0] == 'read' and 4 <= len(command) <= 5: ioh = str(command[1]).lower() typ = str(command[2]).lower() addr = int(command[3]) if len(command) == 4: num = 1 else: num = int(command[4]) read(client=client, addr=addr, ioh=ioh, typ=typ, num=num) elif command[0] == 'write' and len(command) >= 4: typ = str(command[1]).lower() addr = int(command[2]) data = [x for x in command[3:]] write(client=client, addr=addr, typ=typ, data=data) elif command[0] == 'exit': break else: print('Supported commands are:') print('read IOH TYPE ADDRESS [COUNT]') print('write TYPE ADDRESS WORD...') client.close() print('Goodbye\n')
def ask_input(self, theme: str) -> Union[tuple, str]: """ Make a multiline prompt for code input and send the code to the api. The compiled output from the api is returned. """ language = helpers.get_lang() args = helpers.get_args() stdin = helpers.get_stdin() CONSOLE.print( "[green]Enter your code, (press esc + enter to run)[/green]") style = helpers.set_style(theme) CONSOLE.print() code = prompt( "", lexer=PygmentsLexer(lexers_dict[language]), include_default_pygments_style=False, style=style, multiline=True, ) payload = PistonQuery(language=language, args=args, stdin=stdin, code=code) data = services.query_piston(CONSOLE, payload) if len(data["output"]) == 0: return "Your code ran without output.", language return data["output"].split("\n"), language
def run(self): """ Main entry function. """ history = InMemoryHistory() self._load_file() while True: # (re)load the todo.txt file (only if it has been modified) try: user_input = prompt(u'topydo> ', history=history, completer=self.completer, complete_while_typing=False) user_input = shlex.split(user_input) except EOFError: sys.exit(0) except KeyboardInterrupt: continue except ValueError as verr: error('Error: ' + str(verr)) continue try: (subcommand, args) = get_subcommand(user_input) except ConfigError as ce: error('Error: ' + str(ce) + '. Check your aliases configuration') continue try: if self._execute(subcommand, args) != False: self._post_execute() except TypeError: print(GENERIC_HELP)
def initCommand(self): print("CV 1.0.0(default, Oct 12 2017)") print("Type 'info' for more information") print("PyCV 1.0.0") while True: try: self.num += 1 user_input = prompt( history=FileHistory('history.txt'), enable_history_search=True, auto_suggest=AutoSuggestFromHistory(), lexer=CVLexer, completer=CVCompleter(), get_prompt_tokens=self.get_prompt_tokens, get_bottom_toolbar_tokens=self.get_bottom_toolbar_tokens, style=CommandLineStyle, refresh_interval=1, get_title=self.get_title, on_abort=AbortAction.RETRY, # multiline=True, # get_continuation_tokens=self.continuation_tokens, # mouse_support=True, ) click.secho('CV > Out[%d] -> ' % (self.num), nl=False, fg='white') click.echo(user_input) # click.echo_via_pager(user_input) except EOFError: break
def cmd_jshell(ip, port, verbose): global hook_js hook_js = hook_js.format(ip=ip, port=port) print('>>> Listening on {}:{}. Waiting for a victim connection.'.format(ip, port)) eventloop = asyncio.get_event_loop() eventloop.run_until_complete(websockets.serve(handler, ip, port, create_protocol=MyWebSocketServerProtocol)) thread = threading.Thread(target=eventloop.run_forever) thread.start() completer = WordCompleter(completer_list + list(runner.internal_commands) + list(runner.external_commands)) history = InMemoryHistory() while True: if not thread.is_alive(): break cmd = prompt('$ ', patch_stdout=True, completer=completer, history=history, lexer=PygmentsLexer(JavascriptLexer)) if cmd: if cmd == '_help': runner.cmd_help() elif runner.sessions: queue.put_nowait(cmd) else: print('>>> No active session!')
def main(): text = prompt( "Give some animals: ", completer=animal_completer, complete_style=CompleteStyle.READLINE_LIKE, ) print("You said: %s" % text)
def promptOptions(msg, options, default=None): tokens = [ (Token.Sigil, "* "), (Token.Prompt, msg), (Token.Symbol, " ["), ] first = True for option in options: if first: first = False else: tokens.append((Token.Symbol, ",")) if option == default: tokens.append((Token.Default, option.upper())) else: tokens.append((Token.Option, option)) tokens.append((Token.Symbol, "] : ")) val = prompt(get_prompt_tokens=lambda x: tokens, style=_prompt_styles, validator=_OptionValidator(options, default)) if val: return val.lower().strip() return default
def main(): # pragma: no cover cmd_index = 0 args = parse_args() g.style = None if args.style == 'none' else styles.get_style_by_name( args.style) with ExtendedKazooClient(hosts=args.zk_url, timeout=2, read_only=not args.write) as zkcli: cmdrunner = ZkCommandRunner(zkcli) if args.eval: run_cmd(cmdrunner, args.eval) return print_headers(zkcli) while True: # We need a new completer for each command completer = ZkCompleter(zkcli) try: cmd = prompt(render_prompt(cmd_index, zkcli.read_only), history=history, auto_suggest=auto_suggest, completer=completer, lexer=PygmentsLexer(ZkCliLexer), style=style_from_pygments_cls(g.style), vi_mode=args.input_mode == 'vi') run_cmd(cmdrunner, cmd) except (KeyboardInterrupt, EOFError): if ask_for_confirmation('Quit?', confirm_on_exc=True): break except Exception: raise finally: cmd_index += 1
def pppp(): return prompt( auto_suggest=AutoSuggestFromHistory(), completer=AutomataCompleter(), get_prompt_tokens=get_prompt_tokens, history=history, style=DocumentStyle )
def promptString(msg): tokens = [(Token.Sigil, "* "), (Token.Prompt, msg), (Token.Symbol, " : ")] val = prompt(get_prompt_tokens=lambda x: tokens, style=_prompt_styles, validator=_StringValidator()) if val: return val.strip() return None
def interact(connection): clear() connection.send('Welcome!\n') # Ask for input. result = yield From(prompt(message='Say something: ', async_=True)) # Send output. connection.send('You said: {}\n'.format(result)) connection.send('Bye.\n')
def cli(ctx, env): """Enters a shell for slcli.""" # Set up the environment env = copy.deepcopy(env) env.load_modules_from_python(routes.ALL_ROUTES) env.aliases.update(routes.ALL_ALIASES) env.vars['global_args'] = ctx.parent.params env.vars['is_shell'] = True env.vars['last_exit_code'] = 0 # Set up prompt_toolkit settings app_path = click.get_app_dir('softlayer_shell') if not os.path.exists(app_path): os.makedirs(app_path) complete = completer.ShellCompleter(core.cli) while True: try: line = p_shortcuts.prompt( completer=complete, complete_while_typing=True, auto_suggest=p_auto_suggest.AutoSuggestFromHistory(), ) # Parse arguments try: args = shlex.split(line) except ValueError as ex: print("Invalid Command: %s" % ex) continue if not args: continue # Run Command try: # Reset client so that the client gets refreshed env.client = None core.main(args=list(get_env_args(env)) + args, obj=env, prog_name="", reraise_exceptions=True) except SystemExit as ex: env.vars['last_exit_code'] = ex.code except EOFError: return except ShellExit: return except Exception as ex: env.vars['last_exit_code'] = 1 traceback.print_exc(file=sys.stderr) except KeyboardInterrupt: env.vars['last_exit_code'] = 130
def main(): # Create user interface. hello_world_window() # Enable threading in GTK. (Otherwise, GTK will keep the GIL.) gtk.gdk.threads_init() # Read input from the command line, using an event loop with this hook. # We say `patch_stdout=True`, because clicking the button will print # something; and that should print nicely 'above' the input line. result = prompt('Python >>> ', eventloop=create_eventloop(inputhook=inputhook), lexer=PythonLexer, patch_stdout=True) print('You said: %s' % result)
def main(): # We wrap it in a ThreadedCompleter, to make sure it runs in a different # thread. That way, we don't block the UI while running the completions. slow_completer = SlowCompleter() # Add a bottom toolbar that display when completions are loading. def bottom_toolbar(): return ' Loading completions... ' if slow_completer.loading > 0 else '' # Display prompt. text = prompt('Give some animals: ', completer=slow_completer, complete_in_thread=True, complete_while_typing=True, bottom_toolbar=bottom_toolbar, complete_style=CompleteStyle.MULTI_COLUMN) print('You said: %s' % text)
def main(): # Simple completion menu. print('(The completion menu displays colors.)') prompt('Type an animal: ', completer=AnimalCompleter()) # Multi-column menu. prompt('Type an animal: ', completer=AnimalCompleter(), complete_style=CompleteStyle.MULTI_COLUMN) # Readline-like prompt('Type an animal: ', completer=AnimalCompleter(), complete_style=CompleteStyle.READLINE_LIKE)
def interact(connection): # When a client is connected, erase the screen from the client and say # Hello. connection.send('Welcome!\n') # Display prompt with bottom toolbar. animal_completer = WordCompleter(['alligator', 'ant']) def get_toolbar(): return 'Bottom toolbar...' result = yield From(prompt( 'Say something: ', bottom_toolbar=get_toolbar, completer=animal_completer, async_=True)) connection.send('You said: {}\n'.format(result)) connection.send('Bye.\n')
def continue_prompt(message=""): """Prompt the user to continue or not Returns True when the user type Yes. :param message: message to display :type message: str :rtype: bool """ answer = False message = message + "\n'Yes' or 'No' to continue: " while answer not in ('Yes', 'No'): answer = prompt(message, eventloop=eventloop()) if answer == "Yes": answer = True break if answer == "No": answer = False break return answer
def promptOptions(msg, options, default=None): tokens = [(Token.Sigil, "* "), (Token.Prompt, msg), (Token.Symbol, " ["),] first = True for option in options: if first: first = False else: tokens.append((Token.Symbol, ",")) if option == default: tokens.append((Token.Default, option.upper())) else: tokens.append((Token.Option, option)) tokens.append((Token.Symbol, "] : ")) val = prompt(get_prompt_tokens=lambda x: tokens, style=_prompt_styles, validator=_OptionValidator(options, default)) if val: return val.lower().strip() return default
def run(self): """ Main entry function. """ history = InMemoryHistory() while True: # (re)load the todo.txt file (only if it has been modified) self._load_file() try: user_input = prompt(u'topydo> ', history=history, completer=self.completer, complete_while_typing=False) user_input = shlex.split(user_input) except EOFError: sys.exit(0) except KeyboardInterrupt: continue except ValueError as verr: error('Error: ' + str(verr)) continue mtime_after = _todotxt_mtime() try: (subcommand, args) = get_subcommand(user_input) except ConfigError as ce: error('Error: ' + str(ce) + '. Check your aliases configuration') continue # refuse to perform operations such as 'del' and 'do' if the # todo.txt file has been changed in the background. if subcommand and not self.is_read_only(subcommand) and self.mtime != mtime_after: error("WARNING: todo.txt file was modified by another application.\nTo prevent unintended changes, this operation was not executed.") continue try: if self._execute(subcommand, args) != False: self._post_execute() except TypeError: usage()
def main(): text = prompt('Give some animals: ', completer=animal_completer, complete_style=CompleteStyle.READLINE_LIKE) print('You said: %s' % text)
def get_command(): return prompt(completer=completer, history=history, **prompt_kwargs)
#!/usr/bin/env python """ For testing: test to make sure that everything still works when gevent monkey patches are applied. """ from __future__ import unicode_literals from gevent.monkey import patch_all from prompt_toolkit.shortcuts import prompt, create_eventloop if __name__ == '__main__': # Apply patches. patch_all() # There were some issues in the past when the event loop had an input hook. def dummy_inputhook(*a): pass eventloop = create_eventloop(inputhook=dummy_inputhook) # Ask for input. answer = prompt('Give me some input: ', eventloop=eventloop) print('You said: %s' % answer)
from prompt_toolkit.shortcuts import prompt from prompt_toolkit.styles import style_from_pygments from prompt_toolkit.layout.lexers import PygmentsLexer from pygments.styles.tango import TangoStyle from pygments.token import Token from pygments.lexers import HtmlLexer our_style = style_from_pygments( TangoStyle, { Token.Comment: '#888888 bold', Token.Keyword: '#ff88ff bold', } ) text = prompt('Enter HTML: ', lexer=PygmentsLexer(HtmlLexer), style=our_style) print('You said: {}'.format(text))
def main(): text = prompt('Give some animals: ', completer=animal_completer, complete_style=CompleteStyle.MULTI_COLUMN) print('You said: %s' % text)
def main(): text = prompt('Give some animals: ', completer=animal_completer, complete_while_typing=True) print('You said: %s' % text)
def cmd_jshell(ip, port, verbose): """Control a web browser through Websockets. Bind a port (default: 3333) and listen for HTTP connections. On connection, send a JavaScript code that opens a WebSocket that can be used to send commands to the connected browser. You can write the commands directly in the shell, or use plugins, that are simply external JavaScript files. Using habu.jshell you can completely control a web browser. Reference: https://developer.mozilla.org/en-US/docs/Web/API/WebSockets_API Example: \b $ habu.jshell >> Listening on 192.168.0.10:3333. Waiting for a victim connection. >> HTTP Request received from 192.168.0.15. Sending hookjs >> Connection from 192.168.0.15 $ _sessions 0 * 192.168.0.15:33432 Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0 $ _info { "user-agent": "Mozilla/5.0 (X11; Linux x86_64; rv:57.0) Gecko/20100101 Firefox/57.0", "location": "http://192.168.0.10:3333/", "java-enabled": false, "platform": "Linux x86_64", "app-code-name": "Mozilla", "app-name": "Netscape", "app-version": "5.0 (X11)", "cookie-enabled": true, "language": "es-AR", "online": true } $ document.location http://192.168.0.10:3333/ """ global hook_js hook_js = hook_js.format(ip=ip, port=port) print('>>> Listening on {}:{}. Waiting for a victim connection.'.format(ip, port)) eventloop = asyncio.get_event_loop() eventloop.run_until_complete(websockets.serve(handler, ip, port, create_protocol=MyWebSocketServerProtocol)) thread = threading.Thread(target=eventloop.run_forever) thread.start() completer = WordCompleter(completer_list + list(runner.internal_commands) + list(runner.external_commands)) history = InMemoryHistory() while True: if not thread.is_alive(): break cmd = prompt('$ ', patch_stdout=True, completer=completer, history=history, lexer=PygmentsLexer(JavascriptLexer)) if cmd: if cmd == '_help': runner.cmd_help() elif runner.sessions: queue.put_nowait(cmd) else: print('>>> No active session!')
def get_command(): return prompt(**options)
def main(): answer = prompt('Give me some input: ', lexer=RainbowLexer()) print('You said: %s' % answer)
def main(): result = prompt(get_prompt, refresh_interval=.5) print('You said: %s' % result)
def prompt(self): try: return prompt(get_prompt_tokens=getPromptTokens, history=self.history, auto_suggest=shellSuggester(), completer=shellCompleter(), lexer=PygmentsLexer(shellLexer)) except EOFError: return "CTRL+D"
def get_command(): return prompt(u'> ', completer=completer, history=history)
def cli(ctx, env): """Enters a shell for slcli.""" # Set up the environment env = copy.deepcopy(env) env.load_modules_from_python(routes.ALL_ROUTES) env.aliases.update(routes.ALL_ALIASES) env.vars['global_args'] = ctx.parent.params env.vars['is_shell'] = True env.vars['last_exit_code'] = 0 # Set up prompt_toolkit settings app_path = click.get_app_dir('softlayer_shell') if not os.path.exists(app_path): os.makedirs(app_path) history = p_history.FileHistory(os.path.join(app_path, 'history')) complete = completer.ShellCompleter(core.cli) while True: def get_prompt_tokens(_): """Returns tokens for the command prompt""" tokens = [] try: tokens.append((token.Token.Username, env.client.auth.username)) tokens.append((token.Token.At, "@")) except AttributeError: pass tokens.append((token.Token.Host, "slcli-shell")) if env.vars['last_exit_code']: tokens.append((token.Token.ErrorPrompt, '> ')) else: tokens.append((token.Token.Prompt, '> ')) return tokens try: line = p_shortcuts.prompt( completer=complete, history=history, auto_suggest=p_auto_suggest.AutoSuggestFromHistory(), get_prompt_tokens=get_prompt_tokens, ) # Parse arguments try: args = shlex.split(line) except ValueError as ex: print("Invalid Command: %s" % ex) continue if not args: continue # Run Command try: # Reset client so that the client gets refreshed env.client = None core.main(args=list(get_env_args(env)) + args, obj=env, prog_name="", reraise_exceptions=True) except SystemExit as ex: env.vars['last_exit_code'] = ex.code except EOFError: return except ShellExit: return except Exception as ex: env.vars['last_exit_code'] = 1 traceback.print_exc(file=sys.stderr) except KeyboardInterrupt: env.vars['last_exit_code'] = 130