kislyuk / argcomplete

Python and tab completion, better together.
https://kislyuk.github.io/argcomplete/
Apache License 2.0
1.41k stars 134 forks source link

completer won't error on invalid argument #325

Closed vser1 closed 3 years ago

vser1 commented 3 years ago

In the given example:

from argcomplete.completers import ChoicesCompleter

parser.add_argument("--protocol", choices=('http', 'https', 'ssh', 'rsync', 'wss'))
parser.add_argument("--proto").completer=ChoicesCompleter(('http', 'https', 'ssh', 'rsync', 'wss'))

compare (assuming the resulting script is called foo):

foo --protocol bar
foo: error: argument protocol: invalid choice: 'bar" (choose from 'http', 'https', 'ssh', 'rsync', 'wss')
foo --proto bar
# no message

Is there a way to raise such an error with completer (as for #137, one of my completion takes a lot of time to complete…) ?

evanunderscore commented 3 years ago

The completer is only considered when you're completing; it has no impact when you are actually running the program. If you want to enforce a restriction on the passed value, you will need to do so within argparse, or by validating the parsed arguments before you use them.

evanunderscore commented 3 years ago

As an example (not tested):

import argcomplete
import argparse

def get_choices(**kwargs):
    # Imagine this is something that takes a long time to compute.
    return ('http', 'https', 'ssh', 'rsync', 'wss')

parser = argparse.ArgumentParser()
parser.add_argument('--proto').completer = get_choices

argcomplete.autocomplete(parser)
args = parser.parse_args()

if args.proto not in get_choices():
    parser.error('invalid proto')