Python click.prompt() Examples

The following are 30 code examples of click.prompt(). 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 click , or try the search function .
Example #1
Source File: terminal.py    From pros-cli2 with Mozilla Public License 2.0 7 votes vote down vote up
def terminal(port):
    click.echo(click.style('NOTE: This is an early prototype of the terminal.'
                           ' Nothing is guaranteed to work.', bold=True))
    if port == 'default':
        if len(prosflasher.ports.list_com_ports()) == 1:
            port = prosflasher.ports.list_com_ports()[0].device
        elif len(prosflasher.ports.list_com_ports()) > 1:
            click.echo('Multiple ports were found:')
            click.echo(prosflasher.ports.create_port_list())
            port = click.prompt('Select a port to open',
                                type=click.Choice([p.device for p in prosflasher.ports.list_com_ports()]))
        else:
            click.echo('No ports were found.')
            click.get_current_context().abort()
            sys.exit()
    ser = prosflasher.ports.create_serial(port, serial.PARITY_NONE)
    term = proscli.serial_terminal.Terminal(ser)
    signal.signal(signal.SIGINT, term.stop)
    term.start()
    while term.alive:
        time.sleep(0.005)
    term.join()
    ser.close()
    print('Exited successfully')
    sys.exit(0) 
Example #2
Source File: stackit_core.py    From stackit with MIT License 6 votes vote down vote up
def select(questions, num):
    print_full_question(questions[num - 1])
    working = True
    while working:
        user_input = click.prompt("Enter b to launch browser, x to return to search, or q to quit")
        if user_input == 'b':
            click.launch(questions[num - 1].json['link'])
        elif user_input == 'q':
            sys.exit()
        elif user_input == 'x':
            click.echo("\n" * 12)
            # Ranging over the 5 questions including the user's choice
            origin = 0
            if not num % NUM_RESULTS:
                origin = num - NUM_RESULTS
            else:
                origin = num - num % NUM_RESULTS
            for j in range(origin, origin + NUM_RESULTS):
                print_question(questions[j], j + 1)
            working = False
        else:
            click.echo(click.style(
                "The input entered was not recognized as a valid choice.",
                fg="red",
                err=True)) 
Example #3
Source File: utils.py    From isitfit with Apache License 2.0 6 votes vote down vote up
def _helper(self):
      # use "default=''" so that the "leave blank to skip" works (instead of click re-prompting until it gets a value)
      import click
      res_prompt = click.prompt('Email to which to share the results (type "skip" to not send email)', type=str, default=self.last_email_val)

      # check if blank
      res_prompt = res_prompt.strip()
      if res_prompt=='skip':
        ping_matomo("/cost/share_email?original=F&provided=F")
        return None

      # quick validate
      # shortest email is: a@b.c
      # Longest email is: shadishadishadishadi@shadishadishadishadi.shadi
      if len(res_prompt) >= 5:
        if len(res_prompt) <= 50:
          if bool(self.EMAIL_REGEX.match(res_prompt)):
            ping_matomo("/cost/share_email?original=F&provided=T")
            return [res_prompt]

      # otherwise, invalid email
      logger.error("Invalid email address: '%s'"%res_prompt)
      raise ValueError 
Example #4
Source File: main.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def get_private_ip_info():

    allocation_method = ""
    ip_address = ""

    allocation_methods = azure.ALLOCATION_METHODS
    click.echo("\nChoose from given ip allocation method")
    for ind, name in enumerate(allocation_methods):
        click.echo("\t {}. {}".format(str(ind + 1), highlight_text(name)))

    while True:
        res = click.prompt("\nEnter the index of allocation methods", default=1)
        if (res > len(allocation_methods)) or (res <= 0):
            click.echo("Invalid index !!! ")

        else:
            allocation_method = allocation_methods[res - 1]
            click.echo("{} selected".format(highlight_text(allocation_method)))
            break

    if allocation_method == "Static":
        ip_address = click.prompt("\nEnter IP Address", default="")

    return {"ip_allocation_method": allocation_method, "ip_address": ip_address} 
Example #5
Source File: main.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def get_custom_vm_image(azure_obj, account_id, location):
    custom_image_id = ""
    custom_images = azure_obj.custom_images(account_id, location)
    custom_image_names = list(custom_images.keys())

    if not custom_image_names:
        click.echo("\n{}".format(highlight_text("No custom image present")))

    else:
        click.echo("\nChoose from given custom images")
        for ind, name in enumerate(custom_image_names):
            click.echo("\t {}. {}".format(str(ind + 1), highlight_text(name)))

        while True:
            res = click.prompt("\nEnter the index of custom image", default=1)
            if (res > len(custom_image_names)) or (res <= 0):
                click.echo("Invalid index !!! ")

            else:
                custom_image = custom_image_names[res - 1]
                custom_image_id = custom_images[custom_image]
                click.echo("{} selected".format(highlight_text(custom_image)))
                break

    return {"source_image_id": custom_image_id, "use_custom_image": True} 
Example #6
Source File: test_utils.py    From isitfit with Apache License 2.0 6 votes vote down vote up
def test_oneInputSetLast(self, ping_matomo):
    """
    # build a fake click command so that the click.prompt will be emulated
    # https://click.palletsprojects.com/en/7.x/testing/?highlight=test#input-streams
    """
    import click
    @click.command()
    def cmd():
      from isitfit.utils import PromptToEmailIfNotRequested
      pte = PromptToEmailIfNotRequested()
      import tempfile
      with tempfile.NamedTemporaryFile() as fh:
        pte.last_email_cl.fn = fh.name # overwrite file to save last-used email
        pte.last_email_cl.set('me@example.com')
        pte.prompt(None)

    # trigger
    from click.testing import CliRunner
    runner = CliRunner()
    result = runner.invoke(cmd, input='\n')
    print(result.__dict__) # in case of exception, this will show details
    assert not result.exception
    assert '[skip]' not in result.output
    assert '[me@example.com]' in result.output 
Example #7
Source File: actions.py    From pdm with MIT License 6 votes vote down vote up
def ask_for_import(project: Project) -> None:
    """Show possible importable files and ask user to decide"""
    importable_files = list(find_importable_files(project))
    if not importable_files:
        return
    stream.echo(
        stream.cyan("Found following files from other formats that you may import:")
    )
    for i, (key, filepath) in enumerate(importable_files):
        stream.echo(f"{i}. {stream.green(filepath.as_posix())} ({key})")
    stream.echo(
        "{}. {}".format(
            len(importable_files),
            stream.yellow("don't do anything, I will import later."),
        )
    )
    choice = click.prompt(
        "Please select:",
        type=click.Choice([str(i) for i in range(len(importable_files) + 1)]),
        show_default=False,
    )
    if int(choice) == len(importable_files):
        return
    key, filepath = importable_files[int(choice)]
    do_import(project, filepath, key) 
Example #8
Source File: cli.py    From psync with MIT License 6 votes vote down vote up
def ask_for_configs():
    remote_path = click.prompt("Remote path", default="~/remote/path")
    ssh_host = click.prompt("SSH host", default="ssh_host")
    ssh_user = click.prompt("SSH username or enter '-' to skip",
                            default="ssh_user")
    ignores = click.prompt("Files or folders to ignore "
                           "(separated by space)", default=" ")

    if ssh_user == "-":
        ssh_user = None

    if ignores.strip():
        ignores = ignores.split(" ")
    else:
        ignores = []

    return psync.generate_config(ssh_user=ssh_user,
                                 ssh_host=ssh_host,
                                 remote_path=remote_path,
                                 ignores=ignores) 
Example #9
Source File: main.py    From calm-dsl with Apache License 2.0 6 votes vote down vote up
def get_field(schema, path, options, type=str, default=None, msg=None):

    field = path[-1]
    field = field.replace("_", " ")
    field = re.sub(r"(?<=\w)([A-Z])", r" \1", field)
    field = field.capitalize()

    if msg is None:
        msg = "Enter {}".format(field)

    data = ""
    while True:
        if not default:
            data = click.prompt(msg, type=type)

        else:
            data = click.prompt(msg, default=default)

        if not validate_field(schema, path, options, data):
            click.echo("data incorrect. Enter again")

        else:
            break

    return data 
Example #10
Source File: test_utils.py    From isitfit with Apache License 2.0 6 votes vote down vote up
def test_oneInputNoLast(self, ping_matomo):
    """
    # build a fake click command so that the click.prompt will be emulated
    # https://click.palletsprojects.com/en/7.x/testing/?highlight=test#input-streams
    """
    import click
    @click.command()
    def cmd():
      from isitfit.utils import PromptToEmailIfNotRequested
      pte = PromptToEmailIfNotRequested()
      import tempfile
      with tempfile.NamedTemporaryFile() as fh:
        pte.last_email_cl.fn = fh.name # overwrite file to save last-used email
        pte.prompt(None)

    # trigger
    from click.testing import CliRunner
    runner = CliRunner()
    result = runner.invoke(cmd, input='me@example.com\n')
    print(result.__dict__) # in case of exception, this will show details
    assert not result.exception
    assert '[skip]' in result.output 
Example #11
Source File: cli_installer.py    From origin-ci-tool with Apache License 2.0 6 votes vote down vote up
def set_cluster_hostname(oo_cfg):
    first_master = next((host for host in oo_cfg.deployment.hosts if host.is_master()), None)
    message = """
You have chosen to install a single master cluster (non-HA).

In a single master cluster, the cluster host name (Ansible variable openshift_master_cluster_public_hostname) is set by default to the host name of the single master. In a multiple master (HA) cluster, the FQDN of a host must be provided that will be configured as a proxy. This could be either an existing load balancer configured to balance all masters on
port 8443 or a new host that would have HAProxy installed on it.

(Optional)
If you want to override the cluster host name now to something other than the default (the host name of the single master), or if you think you might add masters later to become an HA cluster and want to future proof your cluster host name choice, please provide a FQDN. Otherwise, press ENTER to continue and accept the default.
"""
    click.echo(message)
    cluster_hostname = click.prompt('Enter hostname or IP address',
                                    default=str(first_master))
    oo_cfg.deployment.variables['openshift_master_cluster_hostname'] = cluster_hostname
    oo_cfg.deployment.variables['openshift_master_cluster_public_hostname'] = cluster_hostname 
Example #12
Source File: cmd_auth.py    From a2ml with Apache License 2.0 6 votes vote down vote up
def prompt_login(ctx, param, provider):
    system = ctx.params.get('system','production')
    if provider == 'auger':
        username = ctx.params.get('username')
        if not username:
            username = click.prompt('username', default=None)

        organization = ctx.params.get('organization')
        if not organization:
            organization = click.prompt('organization', default=None)

        password = ctx.params.get('password')
        if not password:
            password = click.prompt('password', default=None, confirmation_prompt=False, hide_input=True)

        return {'username':username, 'organization':organization, 'password':password, 'system':system, 'name':provider}
    return {'username':None, 'organization':None, 'password':None, 'system':system, 'name':provider} 
Example #13
Source File: account.py    From uptick with MIT License 6 votes vote down vote up
def allow(ctx, foreign_account, permission, weight, threshold, account):
    """ Add a key/account to an account's permission
    """
    if not foreign_account:
        from bitsharesbase.account import PasswordKey

        pwd = click.prompt(
            "Password for Key Derivation", hide_input=True, confirmation_prompt=True
        )
        foreign_account = format(
            PasswordKey(account, pwd, permission).get_public(), "BTS"
        )
    print_tx(
        ctx.bitshares.allow(
            foreign_account,
            weight=weight,
            account=account,
            permission=permission,
            threshold=threshold,
        )
    ) 
Example #14
Source File: tools.py    From uptick with MIT License 6 votes vote down vote up
def getcloudloginkey(ctx, account):
    """ Return keys for cloudlogin
    """
    from bitsharesbase.account import PasswordKey

    password = click.prompt("Passphrase", hide_input=True).strip()
    t = [["role", "wif", "pubkey", "accounts"]]
    for role in ["owner", "active", "memo"]:
        wif = PasswordKey(account, password, role=role)
        pubkey = format(wif.get_public_key(), ctx.bitshares.rpc.chain_params["prefix"])

        t.append(
            [
                role,
                str(wif.get_private_key()),
                pubkey,
                ctx.bitshares.wallet.getAccountFromPublicKey(pubkey) or "",
            ]
        )

    print_table(t) 
Example #15
Source File: main.py    From soccer-cli with MIT License 6 votes vote down vote up
def get_input_key():
    """Input API key and validate"""
    click.secho("No API key found!", fg="yellow", bold=True)
    click.secho("Please visit {} and get an API token.".format(RequestHandler.BASE_URL),
                fg="yellow",
                bold=True)
    while True:
        confkey = click.prompt(click.style("Enter API key",
                                           fg="yellow", bold=True))
        if len(confkey) == 32:  # 32 chars
            try:
                int(confkey, 16)  # hexadecimal
            except ValueError:
                click.secho("Invalid API key", fg="red", bold=True)
            else:
                break
        else:
            click.secho("Invalid API key", fg="red", bold=True)
    return confkey 
Example #16
Source File: commands.py    From udata with GNU Affero General Public License v3.0 6 votes vote down vote up
def create():
    '''Create a new user'''
    data = {
        'first_name': click.prompt('First name'),
        'last_name': click.prompt('Last name'),
        'email': click.prompt('Email'),
        'password': click.prompt('Password', hide_input=True),
        'password_confirm': click.prompt('Confirm Password', hide_input=True),
    }
    # Until https://github.com/mattupstate/flask-security/issues/672 is fixed
    with current_app.test_request_context():
        form = RegisterForm(MultiDict(data), meta={'csrf': False})
    if form.validate():
        data['password'] = encrypt_password(data['password'])
        del data['password_confirm']
        data['confirmed_at'] = datetime.utcnow()
        user = datastore.create_user(**data)
        success('User(id={u.id} email={u.email}) created'.format(u=user))
        return user
    errors = '\n'.join('\n'.join(e) for e in form.errors.values())
    exit_with_error('Error creating user', errors) 
Example #17
Source File: utils.py    From isitfit with Apache License 2.0 6 votes vote down vote up
def prompt(self, emailTo):
    if emailTo is not None:
      if len(emailTo) > 0:
        # user already requested email
        ping_matomo("/cost/share_email?original=T")
        return emailTo

    # get last used email if available
    self.last_email_val = self.last_email_cl.get()
    if self.last_email_val is None: self.last_email_val='skip'

    # prompt for email
    while True:
      try:
        res = self._helper()
        return res
      except ValueError:
        pass 
Example #18
Source File: auth.py    From floyd-cli with Apache License 2.0 6 votes vote down vote up
def manual_login_success(token, username, password):
    if token:
        # Login using authentication token
        floyd_logger.info(
            "Please paste the authentication token from %s/settings/security.",
            floyd.floyd_web_host)
        access_token = click.prompt('This is an invisible field. Paste token and press ENTER', type=str, hide_input=True)
        access_token = access_token.strip()

        if not access_token:
            floyd_logger.info("Empty token received. Make sure your shell is handling the token appropriately.")
            floyd_logger.info("See docs for help: http://docs.floydhub.com/faqs/authentication/")
            return

    elif username or password:
        access_token = get_access_code_from_password(username, password)
    else:
        return False

    user = AuthClient().get_user(access_token)
    AuthConfigManager.set_access_token(
        AccessToken(username=user.username,
                    token=access_token))
    floyd_logger.info("Login Successful as %s", user.username)
    return True 
Example #19
Source File: main.py    From cycli with MIT License 6 votes vote down vote up
def run(host, port, username, version, timeout, password, logfile, filename, ssl, read_only):
  if version:
    print("cycli {}".format(__version__))
    sys.exit(0)

  if username and not password:
    password = click.prompt("Password", hide_input=True, show_default=False, type=str)

  try:
    cycli = Cycli(host, port, username, password, logfile, filename, ssl, read_only, timeout)
  except AuthError:
    print("Unauthorized. See cycli --help for authorization instructions.")
  except ConnectionError:
    print("Connection refused. Is Neo4j turned on?")
  else:
    cycli.run() 
Example #20
Source File: test_utils.py    From isitfit with Apache License 2.0 5 votes vote down vote up
def test_userInput(self):
    import click
    from click.testing import CliRunner

    class MyWrap:
      def dummyFac(self, emailIn, emailPrompt):
        self.emailOut = None

        @click.command()
        def dummyCmd():
          from isitfit.utils import PromptToEmailIfNotRequested
          pte = PromptToEmailIfNotRequested()
          import tempfile
          with tempfile.NamedTemporaryFile() as fh:
            pte.last_email_cl.fn = fh.name # overwrite file to save last-used email
            # dont set to leave blank # pte.last_email_cl.set('me@example.com')
            self.emailOut = pte.prompt(emailIn)

        # https://stackoverflow.com/q/38143366/4126114
        runner = CliRunner()
        result = runner.invoke(dummyCmd, input=emailPrompt)
        return self.emailOut

    mw = MyWrap()
    actual = mw.dummyFac(None, '\n')
    assert actual is None
    actual = mw.dummyFac(None, 'n\n')
    assert actual is None
    actual = mw.dummyFac(None, 'y\nshadi@abc.com')
    assert actual == ['shadi@abc.com']
    actual = mw.dummyFac(None, 'y\nbla\nshadi@abc.com')
    assert actual == ['shadi@abc.com'] 
Example #21
Source File: conductor.py    From pros-cli2 with Mozilla Public License 2.0 5 votes vote down vote up
def prompt_config(config, options=dict()):
    for key, value in config.items():
        if value['method'] == 'bool':
            options[key] = click.confirm(value['prompt'],
                                         default=options.get(key, value['default']),
                                         prompt_suffix=' ')
        else:  # elif value['method'] = 'str':
            options[key] = click.prompt(value['prompt'],
                                        default=options.get(key, value['default']),
                                        prompt_suffix=' ')
    return options 
Example #22
Source File: utils.py    From isitfit with Apache License 2.0 5 votes vote down vote up
def prompt(self):
    x = []
    x.append("Profiles in AWS credential file:")

    from termcolor import colored
    profile_list_colors = [colored(z, self.w2c.convert(z)) for z in self.profile_list_nocolors]

    x += ["- %s"%z for z in profile_list_colors]
    x.append("")
    x.append("(use `AWS_PROFILE=myprofile isitfit ...` or `isitfit command --profile=myprofile ...` to skip this prompt)")
    x.append("Profile to use")
    y = "\n".join(x)
    return y 
Example #23
Source File: utils.py    From isitfit with Apache License 2.0 5 votes vote down vote up
def ask_feedback():
  # TODO should use a proper feedback gathering method rather than collecting it in matomo
  # but this is a shortcut for now
  print("")
  import click
  a1 = click.prompt("How useful was this? (0: wtf, 1: useless, 2: IDK, 3: kind of, 4: epiphanic)", type=click.IntRange(0, 4))
  ping_matomo("/feedback?a1_usefulness=%i"%a1)
  q2 = {
    0: "Seriously? Why?",
    1: "Is there no hope? What can be done?",
    2: "What would make things clearer?",
    3: "What can we improve?",
    4: "TBH, I wasn't expecting this. Really? Why?"
  }
  a2 = click.prompt(q2[a1])
  ping_matomo("/feedback?a2_why=%s"%a2)
  a3a = click.confirm("Shall we schedule a 10-minute phone call?")
  ping_matomo("/feedback?a3a_can_we_call=%s"%b2l(a3a))
  a3b = None
  a3c = None
  if a3a:
    a3b = click.prompt("Phone number with country code")
    ping_matomo("/feedback?a3b_phone=%s"%a3b)
    a3c = click.prompt("Best time to call (include timezone)")
    ping_matomo("/feedback?a3c_time=%s"%a3c)
    print("Perfect! In the mean time, feel free to reach me at shadi@autofitcloud.com")
  else:
    print("Ok. You can always reach me at shadi@autofitcloud.com")

  print("Thanks!") 
Example #24
Source File: utils.py    From edgedb with Apache License 2.0 5 votes vote down vote up
def password_prompt():
    if sys.stdin.isatty():
        return click.prompt('Password', hide_input=True)

    raise click.UsageError(
        'password required and input is not a TTY, please '
        'use --password-from-stdin to provide the password value'
    ) 
Example #25
Source File: cli_installer.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def get_proxy_hosts_excludes():
    message = """
If a proxy is needed to reach HTTP and HTTPS traffic, please enter the
name below. This proxy will be configured by default for all processes
that need to reach systems outside the cluster. An example proxy value
would be:

    http://proxy.example.com:8080/

More advanced configuration is possible if using Ansible directly:

https://docs.openshift.com/enterprise/latest/install_config/http_proxies.html
"""
    click.echo(message)

    message = "Specify your http proxy ? (ENTER for none)"
    http_proxy_hostname = click.prompt(message, default='')

    # TODO: Fix this prompt message and behavior. 'ENTER' will default
    # to the http_proxy_hostname if one was provided
    message = "Specify your https proxy ? (ENTER for none)"
    https_proxy_hostname = click.prompt(message, default=http_proxy_hostname)

    if http_proxy_hostname or https_proxy_hostname:
        message = """
All hosts in your OpenShift inventory will automatically be added to the NO_PROXY value.
Please provide any additional hosts to be added to NO_PROXY. (ENTER for none)
"""
        proxy_excludes = click.prompt(message, default='')
    else:
        proxy_excludes = ''

    return http_proxy_hostname, https_proxy_hostname, proxy_excludes 
Example #26
Source File: cli_installer.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def collect_storage_host(hosts):
    """
    Get a valid host for storage from the user and append it to the list of
    hosts.
    """
    message = """
Setting up high-availability masters requires a storage host. Please provide a
host that will be configured as a Registry Storage.

Note: Containerized storage hosts are not currently supported.
"""
    click.echo(message)
    host_props = {}

    first_master = next(host for host in hosts if host.is_master())

    hostname_or_ip = click.prompt('Enter hostname or IP address',
                                  value_proc=validate_prompt_hostname,
                                  default=first_master.connect_to)
    existing, existing_host = is_host_already_node_or_master(hostname_or_ip, hosts)
    if existing and existing_host.is_node():
        existing_host.roles.append('storage')
    else:
        host_props['connect_to'] = hostname_or_ip
        host_props['preconfigured'] = False
        host_props['roles'] = ['storage']
        storage = Host(**host_props)
        hosts.append(storage) 
Example #27
Source File: cli_installer.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def get_routingconfig_subdomain():
    click.clear()
    message = """
You might want to override the default subdomain used for exposed routes. If you don't know what this is, use the default value.
"""
    click.echo(message)
    return click.prompt('New default subdomain (ENTER for none)', default='') 
Example #28
Source File: cli_installer.py    From origin-ci-tool with Apache License 2.0 5 votes vote down vote up
def get_ansible_ssh_user():
    click.clear()
    message = """
This installation process involves connecting to remote hosts via ssh. Any
account may be used. However, if a non-root account is used, then it must have
passwordless sudo access.
"""
    click.echo(message)
    return click.prompt('User for ssh access', default='root') 
Example #29
Source File: methods.py    From dyc with MIT License 5 votes vote down vote up
def _prompt_args(self):
        """
        Wrapper for prompting arguments
        """

        def _echo_arg_style(argument):
            """
            Just a small wrapper for echoing args
            Parameters
            ----------
            str argument: argument name
            """
            return click.style("{}".format(argument), fg="red")

        for arg in self.arguments:
            doc_placeholder = "<arg docstring>"
            arg_doc = (
                click.prompt("\n({}) Argument docstring ".format(_echo_arg_style(arg)))
                if not self.placeholders
                else doc_placeholder
            )
            show_arg_type = self.config.get("arguments", {}).get("add_type", False)
            if show_arg_type:
                arg_placeholder = "<type>"
                arg_type = (
                    click.prompt("({}) Argument type ".format(_echo_arg_style(arg)))
                    if not self.placeholders
                    else arg_placeholder
                )
            self.arg_docstring.append(dict(type=arg_type, doc=arg_doc, name=arg)) 
Example #30
Source File: methods.py    From dyc with MIT License 5 votes vote down vote up
def _prompt_docstring(self):
        """
        Simple prompt for a method's docstring
        """
        if self.placeholders:
            self.method_docstring = "<docstring>"
        else:
            echo_name = click.style(self.name, fg="green")
            self.method_docstring = click.prompt(
                "\n({}) Method docstring ".format(echo_name)
            )