Python inquirer.List() Examples

The following are 11 code examples of inquirer.List(). 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 inquirer , or try the search function .
Example #1
Source File: recover.py    From QR-secret-sharing with MIT License 6 votes vote down vote up
def main():
    # Enter shares
    shares = [raw_input('Enter your share: ')]
    while True:
        questions = [
            inquirer.List('share',
                        message='Enter next share',
                        choices=['OK', 'I don\'t have another one'],
                    ),
        ]
        answer = inquirer.prompt(questions)['share']
        if answer != 'OK':
            break
        shares.append(raw_input('Enter your share: '))

    # Recover
    wait = animation.Wait('spinner', 'Generating randomness.. It may take a while.. ')
    wait.start()
    message = PlaintextToHexSecretSharer.recover_secret(shares)
    wait.stop()
    print('Original message:\n'+message) 
Example #2
Source File: check_ctf.py    From lswriteups with MIT License 5 votes vote down vote up
def get_url(name):
    """Get URL of the specific event

    :name: Name of the CTF entered by user

    :return: A url of to the tasks of the CTF
            eg: https://ctftime.org/event/683/tasks/
    """

    spinner = Halo(text="Finding the URL", spinner="moon", color="red")
    spinner.start()
    past_ctfs = await past_events()
    ctfs = get_event(past_ctfs, name)

    if not ctfs:
        spinner.fail(colors("No CTF found", "32"))
        return

    if len(ctfs) != 1:
        spinner.stop()
        tables = [i["name"] for i in ctfs]
        question = [
            inquirer.List("choice", message="Choose one from below?", choices=tables)
        ]
        answer = inquirer.prompt(question)

        # Compare answer with name of CTF to get a link
        choice = list(filter(lambda ctf: ctf["name"] == answer["choice"], ctfs))
        url = ROOT_URL + choice[0]["link"] + "/tasks/"
        return url

    spinner.succeed("Got it")
    return ROOT_URL + ctfs[0]["link"] + "/tasks/" 
Example #3
Source File: check_ctf.py    From lswriteups with MIT License 5 votes vote down vote up
def show_prev_events():
    events = await past_events()
    ctfs = [i for i in events.keys()]
    question = [
        inquirer.List("choice", message="Choose one from below?", choices=ctfs[:10])
    ]
    answer = inquirer.prompt(question)

    return ROOT_URL + events[answer["choice"]] + "/tasks/" 
Example #4
Source File: cli.py    From aws-sso with Apache License 2.0 5 votes vote down vote up
def configure(args):
    profile = args.profile
    cfg = Configuration()
    params = config_override(cfg.config, profile, args)

    try:
        inquirer.prompt([
            inquirer.Text('url', message='URL', default=params.get('url', ''), validate=validate_url),
            inquirer.Text('aws_profile', message='AWS CLI profile', default=params.get('aws_profile', profile), validate=validate_empty),
            inquirer.Text('username', message='Username', default=params.get('username', ''), validate=validate_empty)
        ], answers=params, raise_keyboard_interrupt=True)
        secrets = SecretsManager(params.get('username'), params.get('url'))
        password = inquirer.password(message='Password', default=secrets.get('credentials', ''), validate=validate_empty)

        token = __get_or_refresh_token(
            params['url'], params['username'], password,
            secrets, cfg.configdir, args.force_refresh, args.headless, args.spinner
        )
        sso = SSOClient(token, params['region'])

        instances = sso.get_instances()
        inquirer.prompt([
            inquirer.List(
                'instance_id',
                message='AWS Account',
                choices=[(_['name'], _['id']) for _ in instances]
            )
        ], answers=params, raise_keyboard_interrupt=True)

        profiles = sso.get_profiles(params['instance_id'])
        inquirer.prompt([
            inquirer.List(
                'profile_id',
                message='AWS Profile',
                choices=[(_['name'], _['id']) for _ in profiles]
            )
        ], answers=params, raise_keyboard_interrupt=True)

        cfg.save()
    except KeyboardInterrupt:
        sys.exit(1) 
Example #5
Source File: printing.py    From shallow-backup with MIT License 5 votes vote down vote up
def prompt_yes_no(message, color, invert=False):
	"""
	Print question and return True or False depending on user selection from list.
	"""
	questions = [inquirer.List('choice',
	                           message=color + Style.BRIGHT + message + Fore.BLUE,
	                           choices=(' No', ' Yes') if invert else (' Yes', ' No')
	                           )
	             ]

	answers = inquirer.prompt(questions)
	if answers:
		return answers.get('choice').strip().lower() == 'yes'
	else:
		sys.exit(1) 
Example #6
Source File: prompts.py    From shallow-backup with MIT License 5 votes vote down vote up
def remove_from_config_prompt():
	"""
	Sequence of prompts for a user to remove a path from the config.
	2-layer selection screen. First screen is for choosing dot or
	config, and then next selection is for the specific path.
	"""
	# Get section to display.
	section_prompt = [inquirer.List('choice',
	                                message=Fore.GREEN + Style.BRIGHT + "Which section would you like to remove a path from?" + Fore.BLUE,
	                                choices=[' Dotfiles',
	                                         ' Dotfolders',
	                                         ' Configs'
	                                    ])
	]

	config = get_config()
	section = inquirer.prompt(section_prompt).get('choice').strip().lower()
	if section == "configs":
		section = "config_mapping"
	paths = config[section]
	# Get only backup paths, not dest paths if it's a dictionary.
	if isinstance(paths, dict):
		paths = list(paths.keys())

	path_prompt = [inquirer.List('choice',
	                             message=Fore.GREEN + Style.BRIGHT + "Select a path to remove." + Fore.BLUE,
	                             choices=paths)
	]
	path_to_remove = inquirer.prompt(path_prompt).get('choice')
	print_blue_bold("Removing {} from backup...".format(path_to_remove))
	paths.remove(path_to_remove)
	config[section] = paths
	write_config(config) 
Example #7
Source File: configure.py    From cclyzer with MIT License 5 votes vote down vote up
def interact(self):
        import inquirer

        dialog = [
            inquirer.List(
                EntryPointsOption.label(),
                message="Choose analysis entry points",
                choices=EntryPointsOption.messages(),
            ),
        ]
        self.options = inquirer.prompt(dialog) 
Example #8
Source File: stronghold.py    From stronghold with MIT License 5 votes vote down vote up
def prompt_yes_no(top_line="", bottom_line=""):
	"""Print question and return True or False depending on user selection from list.
	bottom_line should be used for one liners. Otherwise, it's the second line you want printed.

	Deprecated comment: Thanks, @shobrook"""

	# One liner. Only bottom_line should be printed + stylized
	if top_line is "":
		questions = [inquirer.List('choice',
		                           message=Fore.GREEN + Style.BRIGHT + bottom_line + Fore.YELLOW,
		                           choices=[' Yes', ' No'],
		                           ),
		             ]

	# else top_line is not ""
	else:
		print(Fore.GREEN + Style.BRIGHT + " " + top_line)
		questions = [inquirer.List('choice',
		                           message=Fore.GREEN + bottom_line + Fore.YELLOW,
		                           choices=[' Yes', ' No'],
		                           ),
		             ]

	answers = inquirer.prompt(questions)

	return answers.get('choice').strip() == 'Yes' 
Example #9
Source File: __main__.py    From bridgy with MIT License 4 votes vote down vote up
def prompt_targets(question, targets=None, instances=None, multiple=True, config=None, type=InstanceType.ALL, filter_sources=tuple()):
    if targets == None and instances == None or targets != None and instances != None:
        raise RuntimeError("Provide exactly one of either 'targets' or 'instances'")

    if targets:
        instances = inventory.search(config, targets, filter_sources=filter_sources, type=type)

    if len(instances) == 0:
        return []

    if len(instances) == 1:
        return instances

    display_instances = collections.OrderedDict()
    # TODO: fix cap'd length... it's pretty arbitraty
    maxLen = min(max([len(instance.name) for instance in instances]), 55)
    for instance in sorted(instances):
        display = str("%-" + str(maxLen+3) + "s (%s)") % (instance.name, instance.address)
        display_instances[display] = instance

    questions = []

    if multiple:
        question = inquirer.Checkbox('instance',
                                     message="%s%s%s (space to multi-select, enter to finish)" % (utils.term.bold + utils.term.underline, question, utils.term.normal),
                                     choices=list(display_instances.keys()) + ['all'],
                                     # default='all'
                                     )
    else:
        question = inquirer.List('instance',
                                 message="%s%s%s (enter to select)" % (utils.term.bold, question, utils.term.normal),
                                 choices=list(display_instances.keys()),
                                 )
    questions.append(question)

    answers = None
    try:
        answers = inquirer.prompt(questions, theme=THEMER, raise_keyboard_interrupt=True)
    except KeyboardInterrupt:
        logger.error("Cancelled by user")
        sys.exit(1)

    if 'all' in answers["instance"]:
        selected_hosts = instances
    else:
        selected_hosts = []
        if not multiple:
            answers["instance"] = [answers["instance"]]
        for answer in answers["instance"]:
            selected_hosts.append(display_instances[answer])

    return selected_hosts 
Example #10
Source File: prompts.py    From shallow-backup with MIT License 4 votes vote down vote up
def add_to_config_prompt():
	"""
	Prompt sequence for a user to add a path to the config file under
	either the dot or config sections.
	"""
	add_prompt = [inquirer.List('choice',
	                            message=Fore.GREEN + Style.BRIGHT + "Which section would you like to add this to?" + Fore.BLUE,
	                            choices=[' Dots',
	                                     ' Configs',
	                                     ])
	]

	section = inquirer.prompt(add_prompt).get('choice').strip().lower()
	config = get_config()

	# Prompt until we get a valid path.
	while True:
		print_green_bold("Enter a path to add to {}:".format(section))
		expanded_path = expand_to_abs_path(input())
		split_path = expanded_path.split("/")

		# Check if path exists.
		if not os.path.exists(expanded_path):
			print_red_bold("ERR: {} doesn't exist.".format(expanded_path))
			continue

		config_key = None
		if section == "dots":
			# Make sure it's actually a dotfile
			if split_path[-1][0] != ".":
				print_red_bold("ERR: Not a dotfile.")
				continue

			# Determine if adding to dotfiles or dotfolders
			if not os.path.isdir(expanded_path):
				config_key = "dotfiles"
				print_blue_bold("Adding {} to dotfile backup.".format(expanded_path))
			else:
				config_key = "dotfolders"
				print_blue_bold("Adding {} to dotfolder backup.".format(expanded_path))

			# Add path to config ensuring no duplicates.
			updated_config_key = set(config[config_key] + [path])
			config[config_key] = list(updated_config_key)
			write_config(config)
			break

		elif section == "config":
			# Prompt for folder name
			print_green_bold("Enter a name for this config:")
			dir_name = input()
			config_key = "config_mapping"
			to_add_to_cfg = (expanded_path, dir_name)
			print_blue_bold("Adding {} to config backup.".format(expanded_path))

			# Get dictionary of {path_to_backup: dest, ...}
			config_path_dict = config[config_key]
			config_path_dict[to_add_to_cfg[0]] = to_add_to_cfg[1]
			config[config_key] = config_path_dict
			write_config(config)
			break 
Example #11
Source File: prompts.py    From shallow-backup with MIT License 4 votes vote down vote up
def main_menu_prompt():
	"""
	Prompt user for an action.
	"""
	questions = [inquirer.List('choice',
	                           message=Fore.GREEN + Style.BRIGHT + "What would you like to do?" + Fore.BLUE,
	                           choices=[' Back up all',
	                                    ' Back up configs',
	                                    ' Back up dotfiles',
	                                    ' Back up fonts',
	                                    ' Back up packages',
	                                    ' Reinstall all',
	                                    ' Reinstall configs',
	                                    ' Reinstall dotfiles',
	                                    ' Reinstall fonts',
	                                    ' Reinstall packages',
	                                    ' Add path to config',
	                                    ' Remove path from config',
	                                    ' Show config',
	                                    ' Destroy backup'
	                                    ],
	                           ),
	             ]

	answers = inquirer.prompt(questions)

	if answers:
		return answers.get('choice').strip().lower()
	else:
		# KeyboardInterrupts
		sys.exit(1)