Search code examples
pythonpromptpython-click

click custom option prompt function


I have noticed that prompt using click accepts inputs with trailing spaces

ftp_server = click.prompt("FTP Server")

Is there a way to use a custom return function like this to reject trailing spaces?

def custom_prompt(value):
    if value.strip():
        return True
    else:
        return False

ftp_server = click.prompt("FTP Server", custom_prompt)

I have already used this:

while not ftp_server.strip():
    ftp_server = click.prompt("FTP Server")

But I'm looking for a better way because I don't want to use a while loop each time I use prompt.


Solution

  • To reject invalid user input, you can use the value_proc parameter to click.prompt. A validator to reject input with trailing spaces could look like:

    Prompt Validator

    import click
    
    def validate_no_trailing_space(value):
        if value != value.rstrip():
            raise click.UsageError("Trailing space is invalid!")
        return value
    
    ftp_server = click.prompt("FTP Server",
                              value_proc=validate_no_trailing_space)
    

    Trim Spaces

    You might also consider a validator which trims leading and trailing spaces but reject spaces in the name:

    def validate_no_internal_space(value):
        value = value.strip()
        if ' ' in value:
            raise click.UsageError("Spaces are not valid here!")
        return value