Does Python Click prompt have any prefill options?

Viewed 149

I'm trying to allow users to edit a parameter from a config file using Click. What I would like to do is present them with the previous parameter prefilled in a prompt input so that they can edit it directly, rather than making them type it all out again. For example, if the parameter is 'test.com', I'd like my prompt to present something like this:

Edit Domain Name: testdomain.com

With the testdomain.com being editable. Then when they add a 1 so it reads testdomain1.com, the prompt returns testdomain1.com back to the code. There are a couple other posts from 10 years ago with readline and other more vanilla-python-like options like here and here, but nothing that I can figure out from the Click documentation.

Anyone have any ideas? Thanks!

1 Answers

Prompts are not the most user-friendly for editing text.
Fortunately, there is a way around this.

Take, for example, git commit.
If you don't specify the --message or -m option, git commit opens up an editor for the user to type a commit message in.

You might want to consider prompting your users with a text-editor too.
You can achieve this with python-click as follows:

import click

def promp_user_with_editor(old_param: str) -> str:
    comment = "# Edit Domain Name:\n"
    editor_content = f"{comment}{old_param}"
    result = click.edit(editor_content)
    # In real code, you would properly handle the user's input here.
    new_param = result.split(comment)[1].strip()
    return new_param

@click.command()
def main():
    new_param = promp_user_with_editor(old_param="testdomain.com")
    click.echo(f"{new_param=}")

if __name__ == "__main__":
    main()

Now running this code as:

python3 the_name_of_the_above_file.py

Will prompt me with:

# Edit Domain Name:
testdomain.com

If I change that to:

# Edit Domain Name:
stackoverflow.com

The output is:

new_param='stackoverflow.com'
Related