multimeric / ArgparsePrompt

Wrapper for the built-in Argparse, allowing missing command-line arguments to be filled in by the user via interactive prompts
GNU General Public License v3.0
11 stars 4 forks source link

Support for positional arguments #11

Open aspitarl opened 2 years ago

aspitarl commented 2 years ago

I have a script with a required argument 'datestr' that I usually provide as a positional argument

parser.add_argument('datestr', type=str, help='Provide a date to process in the format YYYY-MM-DD')

This does not work with PromptParser giving error: the following arguments are required: datestr. However, this does work when changing to an 'optional' argument.

parser.add_argument('-d', '--datestr', type=str, help='Provide a date to process in the format YYYY-MM-DD')

Where it works as expected.

It seems like the behavior of both arguments should be the same with PromptParser. Unless I'm missing something, I'm guessing this is just not implemented yet. This seems like it would be useful as positional arguments are usually required.

multimeric commented 2 years ago

I think what's happening here is that the check for "is this required argument present" runs before the type function executes, so we never have the chance to intercept the argparse behaviour when it's required. I'm not sure, but I don't think there's any easy way to solve this without either monkey patching argparse (which wouldn't be good), or else rewriting argparse itself.

In your case I recommend setting the argument to optional, but then pass in a type function that checks that it's not null and throws a ArgumentTypeError, TypeError, or ValueError if it is. This should work well enough, although the error message might appear slightly different to base argparse in this case.

multimeric commented 2 years ago

Actually this solution could easily be pushed up into the repo: