0

Using click is there a way to programmatically prompt a user for an input.

For some use cases, I have been able to create a custom class to make certain options required and prompt the user for input (or more accurately make an existing option no longer required and remove a prompt) inspired from this post.

For use cases where I need an unknown number of the same type of input, I could code a large number of options and then remove those that are not needed. But, a more elegant solution would be to programmatically generate options from a custom class from a single argument or option. Any suggestions would be appreciated.

K Stewart
  • 23
  • 7
  • These sorts of questions are much easier to answer with a concrete example and code showing what you tried to do and how it was not what you were after. – Stephen Rauch Jul 30 '20 at 03:31

1 Answers1

0

This is what I came up with to replicate the desired behavior.

In this use case, the user has already downloaded a file with some number of unsigned messages (n_messages). The user then signs the messages via a separate process. And, then uploads the signed messages along with a file that contains the unsigned messages using the @click.command signed.

Here is the @click.command:

@main.command()
@ click.argument('file', type=click.File('r'), required=True)
@click.option('-sig', 'signatures', type=click.File('r'), multiple=True, required=True, cls=VerifySigNumbers)
def signed(*args, **kwargs):
    create_signed_tx(*args, **kwargs)

Here is the custom class:

class VerifySigNumbers(click.Option):
def __init__(self, *args, **kwargs):
    super(VerifySigNumbers, self).__init__(*args, **kwargs)

def handle_parse_result(self, ctx, opts, args):
    pig_file = opts.get('file')
    data = read_pig_file(file)
    n_messages = data.get('n_messages')
    signatures = opts.get('signatures')
    n_sigs = 0 if signatures is None else len(signatures)

    if n_sigs != n_messages:
        raise click.UsageError(
            f'{pig_file} requires {n_tx_inputs} signatures, {n_sigs} provided', ctx)

    return super(VerifySigNumbers, self).handle_parse_result(ctx, opts, args)

I would like the users to be prompt for the unsigned messages, but unsure how to implement it. Additionally, I ran into an issue uploading files via a prompt.

K Stewart
  • 23
  • 7