def main(): """Classic syntax example.""" questions = [ {"type": "input", "message": "Enter your name:"}, { "type": "input", "message": "Which company would you like to apply:", "completer": { "Google": None, "Facebook": None, "Amazon": None, "Netflix": None, "Apple": None, "Microsoft": None, }, "multicolumn_complete": True, }, { "type": "input", "message": "What's your salary expectation(k):", "transformer": lambda result: "%sk" % result, "filter": lambda result: int(result) * 1000, "validate": NumberValidator(), }, ] result = prompt(questions)
def display_equipment_choices( self, player: IPlayer) -> Union[str, bool, list, IEquipmentItem]: equipments = player.bag.get_equipments() choices = [] for equip in equipments: equipped_string = '' if player.equipment.is_equipped(equip): equipped_string = ' (EQUIPPED)' choices.append({ 'name': emojis.encode('{item} - {tier} {equipped_string}'.format( item=equip.name, tier=equip.tier, equipped_string=equipped_string)), 'value': equip }) choices.append({'name': emojis.encode('Cancel :x: '), 'value': None}) equipment_questions = [{ 'type': 'list', 'message': 'Select an Equipment:', 'choices': choices, 'invalid_message': 'You need to select at least one item', 'show_cursor': True, 'max_height': '100' }] result = prompt(questions=equipment_questions) selected_equipment = result[0] return selected_equipment
def main(): questions = [ { "type": "list", "message": "Select an action:", "choices": ["Upload", "Download", Choice(value=None, name="Exit")], "default": None, }, { "type": "list", "message": "Select regions:", "choices": [ Choice("ap-southeast-2", name="Sydney"), Choice("ap-southeast-1", name="Singapore"), Separator(), "us-east-1", "us-east-2", ], "multiselect": True, "transformer": lambda result: f"{len(result)} region{'s' if len(result) > 1 else ''} selected", "when": lambda result: result[0] is not None, }, ] result = prompt(questions=questions)
def perform_character_creation_questions( self, existing_names: List[str]) -> Union[str, bool, list, dict]: questions = [ { "type": "input", "message": emojis.encode(':man: Please enter your character name '), "validate": DuplicatedNamesValidator(existing_names), "invalid_message": "minimum of 1 letters, max of 20 letters", "name": "nickname" }, { "type": "list", "message": emojis.encode(':skull: Please enter your character race? '), "choices": get_configuration(RACES_SECTION).keys(), "name": "race" }, { "type": "list", "message": emojis.encode( ':name_badge: Please enter your character job? '), "choices": get_configuration(JOBS_SECTION).keys(), "name": "job" }, ] return prompt(questions)
def get_saved_game( self, normalized_files: List[Dict]) -> Union[str, bool, list, Path]: choices = [] for file_dict in normalized_files: option = { 'name': file_dict.get('name'), 'value': file_dict.get('path') } choices.append(option) choices.append({ 'name': emojis.encode('Cancel :x:'), 'value': 'cancel' }) select_saved_game_questions = [{ 'type': 'list', 'message': 'Select a game to continue: ', 'choices': choices, 'invalid_message': 'You need to select at least one enemy to check!', 'show_cursor': True, 'max_height': '100' }] result = prompt(questions=select_saved_game_questions) return result[0]
def interactive_cmd(opt1, *args): from InquirerPy import prompt, inquirer def add_points(lst): for j in lst: key = list(j.keys())[0] val = "> " + list(j.values())[0] j.update({key: val}) return lst opt1 = add_points(opt1) back = True while back is True: exit_option = [{"name": "-- exit", "value": "exit"}] question1 = [ { "type": "list", "message": "What category of templates are you interested in? (use arrows to navigate)", "choices": opt1 + exit_option, }, ] result1 = prompt(questions=question1) if result1[0] == "exit": raise IOError options2 = args[result1[0]] back_option = [{"name": "-- back", "value": True}] question2 = [ { "type": "list", "message": "Choose template you wish to create. (use arrows to navigate)", "choices": options2 + back_option }, ] result2 = prompt(questions=question2) if result2[0] is not True: back = False return result1[0], result2[0]
def main(): scraper = prompt(scraper_question)["scraper_type"] if scraper == "Tableau": answers = prompt(tableau_questions) state = us.states.lookup(answers["state_name"]) scraper_name = camel_to_snake(answers["name"]) + ".py" path: pathlib.Path = SCRAPER_DIR / state.abbr / scraper_name path.parent.mkdir(exist_ok=True, parents=True) with open(path, "w") as f: template = ENV.get_template("tableau.py") content = template.render(scraper=answers) f.write(content) print(f"Created scraper at {path}") else: raise NotImplementedError(f"Not ready for scraper of type {scraper}")
def confirm_item_selection(self) -> Union[str, bool, list, bool]: questions = [ { "type": "confirm", "message": "Are you sure?", "name": "confirm", "default": False }, ] result = prompt(questions) confirm = result["confirm"] return confirm
def confirm_use_item_on_you(self) -> Union[str, bool, list, bool]: questions = [ { "type": "confirm", "message": "Are you using the item on yourself?", "name": "confirm", "default": False }, ] result = prompt(questions) confirm = result["confirm"] return confirm
def yes_or_no_prompt(prompt_text: str) -> bool: """Prompts user for a (y/n) input Args: prompt (str): Text to display before (y/n) Returns: bool: True -> "y" | False -> "n" """ options = { 'type': 'confirm', 'message': prompt_text, 'name': prompt_text } return prompt(options).get(prompt_text)
def main_menu() -> str: """Displays Main Menu for application Returns: str: User Selected Option """ main_menu = { 'type': 'list', 'name': MAIN_MENU_TITLE, 'message': MENU_CHOOSE_PROMPT, 'choices': _get_list_menu_options([REMOVE_RATED_SONGS_FROM_DEFAULT_PLAYLISTS_OPTION, REMOVE_RATED_SONGS_FROM_PLAYLIST_OPTION, REPLACE_UPLOADED_SONGS_WITH_STREAMING_VERSIONS], True, False, False), } return prompt(main_menu).get(MAIN_MENU_TITLE)
def perform_game_create_questions(self) -> Union[str, bool, list, dict]: begin_game_questions = [{ "type": "list", "message": emojis.encode(':video_game: Select the Game Type '), "choices": ["Deathmatch", "Clan"], "name": "game" }, { "type": "list", "message": emojis.encode(':sunrise: Select the map '), "choices": ["Millstone Plains", "Firebend Vulcan", "Lerwick Mountains"], "name": "map" }, { "type": "input", "message": emojis.encode( ':computer: How many controlled players are playing '), "validate": MaxPlayersValidator(), "invalid_message": "Input should be number.", "default": "1", "name": "controlled_players_number" }, { "type": "input", "message": emojis.encode(':computer: How many bots are you playing against '), "validate": MaxBotsInputValidator(), "invalid_message": "Input should be number.", "default": "4", "name": "bots_number" }] return prompt(begin_game_questions)
def config_twilio(): questions = [{ 'type': 'input', 'name': 'sender', 'message': 'Sender name', }, { 'type': 'input', 'name': 'account_sid', 'message': 'Twillio Account SID', }, { 'type': 'input', 'name': 'token', 'message': 'Twillio Auth Token', }] print("== Twillio Client Configuration ==") return prompt(questions)
def main(): questions = [ { "type": "expand", "choices": question1_choice, "message": "Pick your favourite:", "default": "o", "cycle": False, }, { "type": "expand", "choices": question2_choice, "message": "Select your preferred method:", }, ] result = prompt(questions)
def main() -> None: questions = [ { "type": "number", "message": "Enter integer:", "min_allowed": -2, "max_allowed": 10, "validate": EmptyInputValidator(), }, { "type": "number", "message": "Enter float:", "float_allowed": True, "validate": EmptyInputValidator(), }, ] result = prompt(questions)
def uninstall(c): """卸载""" # if not c.config.sudo.password: # c.run('fab uninstall --prompt-for-sudo-password', echo=False) # return result = prompt([{ 'type': 'list', 'message': gettext('uninstall'), 'choices': ['node', 'python', Choice('', gettext('cancel'))] }]) if result[0] == 'python': hint('uninstall Python') c.run('brew uninstall [email protected]') c.sudo('rm -rf /usr/local/lib/python3.10/') if result[0] == 'node': hint('uninstall Node.js') c.run('brew uninstall node') c.sudo('rm -rf /usr/local/lib/node_modules/')
def ask_where_to_move( self, possibilities: List[str]) -> Union[str, bool, list, str]: questions = [{ 'type': 'list', 'message': emojis.encode(':mount_fuji: Select where to move: '), 'choices': possibilities, 'invalid_message': 'You need to select at least one place to move!', 'show_cursor': True, 'max_height': '100' }] result = prompt(questions=questions) return result[0]
def main(): questions = [ { "type": "rawlist", "choices": [ "Apple", "Orange", "Peach", "Cherry", "Melon", "Strawberry", "Grapes", ], "message": "Pick your favourites:", "default": 3, "multiselect": True, "transformer": lambda result: ", ".join(result), "validate": lambda result: len(result) > 1, "invalid_message": "Minimum 2 selections", }, { "type": "rawlist", "choices": [ Choice(name="Delivery", value="dl"), Choice(name="Pick Up", value="pk"), Separator(line=15 * "*"), Choice(name="Car Park", value="cp"), Choice(name="Third Party", value="tp"), ], "message": "Select your preferred method:", }, ] result = prompt(questions)
def ask_enemy_to_attack( self, enemies: List[IPlayer], skill_type: str = '') -> Union[str, bool, list, IPlayer]: choices = [] action_type = 'attack: :punch:' if skill_type == 'recover': action_type = 'recover: :green_heart:' elif skill_type == 'buff': action_type = 'buff:' elif skill_type == 'debuff': action_type = 'debuff:' for enemy in enemies: choices.append({ 'name': '{enemy} ({job}) (life: {life})'.format( enemy=enemy.name, job=enemy.job.get_name(), life=enemy.life), 'value': enemy }) choices.append({'name': emojis.encode('Cancel :x: '), 'value': None}) enemies_questions = [{ 'type': 'list', 'message': emojis.encode( 'Select an enemy to {action}'.format(action=action_type)), 'choices': choices, 'invalid_message': 'You need to select at least one enemy to attack!', 'show_cursor': True, 'max_height': '100' }] result = prompt(questions=enemies_questions) selected_enemy = result[0] return selected_enemy
def ask_check_action(self, show_items: bool = False ) -> Union[str, bool, list, str]: """ Ask which kind of information player wants to check. :param bool show_items: If the player doesn't have items on its bag, this flag will help the communicator to remove the items question. :rtype: Union[str, bool, list, str]. """ choices = [{ 'name': emojis.encode('Map and Enemies :city_sunset: '), 'value': 'map' }, { 'name': emojis.encode('My Status: :bar_chart: '), 'value': 'status' }, { 'name': emojis.encode('Single Enemy: :skull: '), 'value': 'enemy' }] if show_items: choices.append({ 'name': emojis.encode('My Items: :test_tube: '), 'value': 'item' }) choices.append({ 'name': emojis.encode('Cancel: :x: '), 'value': 'cancel' }) questions = [{ 'type': 'list', 'message': 'Check: ', 'choices': choices, 'default': 'map', 'invalid_message': 'You need to select at least one check to execute!', 'show_cursor': True, 'max_height': '100' }] result = prompt(questions=questions) return result[0]
def main(): questions = [ { "type": "checkbox", "message": "Select regions:", "choices": question1_choice, "transformer": lambda result: "%s region%s selected" % (len(result), "s" if len(result) > 1 else ""), }, { "type": "checkbox", "message": "Pick your favourites:", "choices": question2_choice, "validate": lambda result: len(result) >= 1, "invalid_message": "should be at least 1 selection", "instruction": "(select at least 1)", }, ] result = prompt(questions)
def perform_first_question(self) -> Union[str, bool, list, str]: choices = [{ 'name': emojis.encode('New Game :new:'), 'value': 'new' }, { 'name': emojis.encode('Continue :repeat:'), 'value': 'continue' }] first_game_questions = [{ 'type': 'list', 'message': 'Select an option: ', 'choices': choices, 'default': 'new', 'invalid_message': 'You need to select at least one game type to play!', 'show_cursor': True, 'max_height': '100' }] result = prompt(questions=first_game_questions) return result[0]
def main(): home_path = "~/" if os.name == "posix" else "C:\\" questions = [ { "type": "filepath", "message": "Enter file to upload:", "name": "location", "default": home_path, "validate": PathValidator(is_file=True, message="Input is not a file"), "only_files": True, }, { "type": "filepath", "message": "Enter path to download:", "validate": PathValidator(is_dir=True, message="Input is not a directory"), "name": "destination", "only_directories": True, }, ] result = prompt(questions)
def main(): questions = [ { "type": "confirm", "message": "Proceed?", "name": "proceed", "default": True, }, { "type": "confirm", "message": "Require 1 on 1?", "when": lambda result: result["proceed"], }, { "type": "confirm", "message": "Confirm?", "when": lambda result: result.get("1", False), }, ] result = prompt(questions)
def main(): questions = [ { "type": "fuzzy", "message": "Select actions:", "choices": ["hello", "weather", "what", "whoa", "hey", "yo"], "default": "he", "max_height": "70%", }, { "type": "fuzzy", "message": "Select preferred words:", "choices": get_choices, "multiselect": True, "validate": lambda result: len(result) > 1, "invalid_message": "minimum 2 selection", "max_height": "70%", }, ] result = prompt(questions=questions)
def select_skill( self, available_skills: List[ISkill]) -> Union[str, bool, list, ISkill]: choices = [] for skill in available_skills: area_range_string = '' if skill.ranged == 0: area_range_string = '/ melee skill' elif skill.ranged > 0 and skill.area == 0: area_range_string = '/ ranged skill with range of {range}, single target'.format( range=skill.ranged) elif skill.ranged > 0 and skill.area > 0: area_range_string = '/ ranged skill with range of {range}, area damage of radius {area}'.format( range=skill.ranged, area=skill.area) choices.append({ 'name': emojis.encode( '{name} / type: {kind} / cost: {cost} mana :blue_heart: {additional}' .format(name=skill.name, kind=skill.kind, cost=skill.cost, additional=area_range_string)), 'value': skill }) choices.append({'name': emojis.encode('Cancel :x: '), 'value': None}) skill_questions = [{ 'type': 'list', 'message': emojis.encode('Select a skill: :fire:'), 'choices': choices, 'default': available_skills[0], 'invalid_message': 'You need to select at least one skill', 'show_cursor': True, 'max_height': '100' }] result = prompt(questions=skill_questions) selected_skill = result[0] return selected_skill
def main(): questions = [ { "type": "password", "message": "Old password:"******"transformer": lambda _: "[hidden]", "validate": lambda text: text == original_password, "invalid_message": "Wrong password", "long_instruction": "Original password: InquirerPy45@", }, { "type": "password", "message": "New password:"******"name": "new_password", "validate": PasswordValidator( length=8, cap=True, special=True, number=True ), "transformer": lambda _: "[hidden]", "long_instruction": "Password require length of 8, 1 cap char, 1 special char and 1 number char.", }, {"type": "confirm", "message": "Confirm?", "default": True}, ] result = prompt(questions)
def select_item(self, items: List[IItem]) -> Union[str, bool, list, IItem]: choices = [] for item in items: choices.append({ 'name': emojis.encode('{item} - {tier}'.format(item=item.name, tier=item.tier)), 'value': item }) choices.append({'name': emojis.encode('Cancel :x: '), 'value': None}) items_questions = [{ 'type': 'list', 'message': 'Select an item:', 'choices': choices, 'default': items[0], 'invalid_message': 'You need to select at least one item', 'show_cursor': True, 'max_height': '100' }] result = prompt(questions=items_questions) selected_item = result[0] return selected_item
def list_selection_menu(title: str, choices: List[dict], prompt_text: str = MENU_CHOOSE_PROMPT, allow_quit: bool = False, allow_skip: bool = False, allow_add_to_skip_list: bool = False) -> dict: """Displays a menu that returns the index of the user selection. Args: title (str): Menu title text choices (List[dict]): Choices to display to the user prompt (str, optional): Optional user prompt text. Defaults to MENU_CHOOSE. allow_quit (bool, optional): Set to True to add a "Quit" option. Defaults to False. allow_skip (bool, optional): Set to True to add a "Skip" option. Defaults to False. allow_add_to_skip_list (bool, optional): Set to True to add a "Add to Skip List" option. Defaults to False. Returns: int: List index of the user selection """ list_menu = { 'type': 'list', 'name': title, 'message': prompt_text, 'choices': _get_list_menu_options(choices, allow_quit, allow_skip, allow_add_to_skip_list), } return prompt(list_menu)
def ask_enemy_to_check( self, enemies: List[IPlayer]) -> Union[str, bool, list, IPlayer]: choices = [] for enemy in enemies: choices.append({ 'name': '{enemy} ({job})'.format(enemy=enemy.name, job=enemy.job.get_name()), 'value': enemy }) enemies_questions = [{ 'type': 'list', 'message': 'Select an enemy:', 'choices': choices, 'invalid_message': 'You need to select at least one enemy to check!', 'show_cursor': True, 'max_height': '100' }] result = prompt(questions=enemies_questions) selected_enemy = result[0] return selected_enemy