How to combine interactive tooltips with argparse in python?

I have a program with a lot of potential arguments. This basically allows the user get/set/delete/listany table in a very small database. Each column has an argument that can be passed. This is not the main interface, but just a useful admin interface.

In any case, if the user wants to insert a row into the table, he must know the name of all the columns. Although it’s easy to see that using it is also a pain in the butt.

So, I changed the code so that the user can pass the --prompt option, and the program will offer them for each column name associated with the table specified by it. But my problem is that now I need to duplicate my input restrictions (selection, types, etc.) In two places - argparse and this hint.

  • Question # 1: is there a better way to do this?
  • Question # 2: Is there a clean way to refer to containment restrictions for this purpose?
  • Question # 3: are there any libraries as alternatives that combine command line arguments, options, and tooltips?

thank

+5
source share
1 answer

A typical way to do this would be through a special action. You may have an argparse option and an input verified using the same function as here.

#!/usr/bin/env python3

import argparse


class ColumnsAction(argparse.Action):
    def __call__(self, parser, namespace, value, option_string=None):
        self.validate(parser, value)
        setattr(namespace, self.dest, value)

    @staticmethod
    def validate(parser, value):
        if value not in ('foo', 'bar'):
            parser.error('{} not valid column'.format(value))


parser = argparse.ArgumentParser()
parser.add_argument('--columns', action=ColumnsAction)
args = parser.parse_args()
if args.columns is None:
    args.columns = input('Enter columns: ')
    ColumnsAction.validate(parser, args.columns)
print(args.columns)
+3
source

All Articles