當前位置: 首頁>>代碼示例>>Python>>正文


Python inquirer.prompt方法代碼示例

本文整理匯總了Python中inquirer.prompt方法的典型用法代碼示例。如果您正苦於以下問題:Python inquirer.prompt方法的具體用法?Python inquirer.prompt怎麽用?Python inquirer.prompt使用的例子?那麽, 這裏精選的方法代碼示例或許可以為您提供幫助。您也可以進一步了解該方法所在inquirer的用法示例。


在下文中一共展示了inquirer.prompt方法的15個代碼示例,這些例子默認根據受歡迎程度排序。您可以為喜歡或者感覺有用的代碼點讚,您的評價將有助於係統推薦出更棒的Python代碼示例。

示例1: main

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
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) 
開發者ID:skewthreads,項目名稱:QR-secret-sharing,代碼行數:23,代碼來源:recover.py

示例2: get_url

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
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/" 
開發者ID:mzfr,項目名稱:lswriteups,代碼行數:35,代碼來源:check_ctf.py

示例3: show_prev_events

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
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/" 
開發者ID:mzfr,項目名稱:lswriteups,代碼行數:11,代碼來源:check_ctf.py

示例4: prompt

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
def prompt(question):
    """Execute prompt answer

    Args:
        question (list): list of inquirer question

    Returns: string of answer

    """
    answers = inquirer.prompt(question)
    return answers['value'] 
開發者ID:blue-oil,項目名稱:blueoil,代碼行數:13,代碼來源:init.py

示例5: configure

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
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) 
開發者ID:wnkz,項目名稱:aws-sso,代碼行數:43,代碼來源:cli.py

示例6: get_initial_config_params

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
def get_initial_config_params():
    ''' Get initial config params from user. '''

    questions = [
        Text(
            'project_name',
            message='Enter your project_name',
        ),

        Text(
            'user',
            message='Enter your SSH username',
            default=DEFAULT_CONFIG['user']
        ),

        Text(
            'ssh_port',
            message='Enter SSH port',
            default=DEFAULT_CONFIG['port']
        ),

        List(
            'deployment_preset',
            message='Select your deployment preset',
            choices=[
                presets.WEB,
                presets.NODE,
                presets.REMOTE_SOURCE
            ]
        ),

        Text(
            'deployment_base_dir',
            message='Enter your base directory for deployment',
            default=DEFAULT_CONFIG['deployment']['base_dir']
        )
    ]

    answers = prompt(questions)

    return answers 
開發者ID:kabirbaidhya,項目名稱:boss,代碼行數:43,代碼來源:inquiries.py

示例7: prompt_yes_no

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
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) 
開發者ID:alichtman,項目名稱:shallow-backup,代碼行數:17,代碼來源:printing.py

示例8: remove_from_config_prompt

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
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) 
開發者ID:alichtman,項目名稱:shallow-backup,代碼行數:35,代碼來源:prompts.py

示例9: main_menu_prompt

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
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) 
開發者ID:alichtman,項目名稱:shallow-backup,代碼行數:33,代碼來源:prompts.py

示例10: interact

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
def interact(self):
        import inquirer

        dialog = [
            inquirer.List(
                EntryPointsOption.label(),
                message="Choose analysis entry points",
                choices=EntryPointsOption.messages(),
            ),
        ]
        self.options = inquirer.prompt(dialog) 
開發者ID:plast-lab,項目名稱:cclyzer,代碼行數:13,代碼來源:configure.py

示例11: prompt_yes_no

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
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' 
開發者ID:alichtman,項目名稱:stronghold,代碼行數:28,代碼來源:stronghold.py

示例12: test_prompt_returns_a_hash

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
def test_prompt_returns_a_hash(self):
        self.assertEqual({}, prompt([])) 
開發者ID:magmax,項目名稱:python-inquirer,代碼行數:4,代碼來源:test_prompt.py

示例13: test_prompt_renders_a_questions

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
def test_prompt_renders_a_questions(self):
        question1 = MagicMock()
        question1.name = 'foo'
        result1 = object()
        render = Mock()
        render.render.return_value = result1

        result = prompt([question1], render=render)

        self.assertEqual({'foo': result1}, result)
        self.assertTrue(render.render.called)
        render.render.call_args_list[0][0] == result1 
開發者ID:magmax,項目名稱:python-inquirer,代碼行數:14,代碼來源:test_prompt.py

示例14: prompt_targets

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
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 
開發者ID:wagoodman,項目名稱:bridgy,代碼行數:54,代碼來源:__main__.py

示例15: add_to_config_prompt

# 需要導入模塊: import inquirer [as 別名]
# 或者: from inquirer import prompt [as 別名]
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 
開發者ID:alichtman,項目名稱:shallow-backup,代碼行數:63,代碼來源:prompts.py


注:本文中的inquirer.prompt方法示例由純淨天空整理自Github/MSDocs等開源代碼及文檔管理平台,相關代碼片段篩選自各路編程大神貢獻的開源項目,源碼版權歸原作者所有,傳播和使用請參考對應項目的License;未經允許,請勿轉載。