How to call a function by a parameter using argparse?

Asked

Viewed 50 times

1

I was able to call functions just by creating subparsers but there are two parameters left that are part of the parser, do you have any correct way to pass a function in the argument statement? Example:

parser.add_argument("-l", "--list", chamar_funcao=nome_da_funcao, help=...)

1 answer

0


All Argparser does is read the command line parameters according to the specification you mount when calling the .add_argument and return an object that has the values of the past options, when you call .parse_args.

If you want to call specific functions, you have to put this into your program, using structures like if getattr(args, ...): (or others):

Example of argparse:

import argparse

def list(param):
    print(f"listagem de coisas: {param}")


def main():
    parser = argparse.ArgumentParser(description='Exemplo')
    parser.add_argument('--list', "-l", type=str,
                        help='Lista os objetos do tipo citado')

    args = parser.parse_args()

    if getattr(args, "list", None):
        list(args.list)
    else:
        print("Nenhuma opção passada")

if __name__ == "__main__":
    main()

The documentation of argparse is pretty crazy - because she, from the first example, puts objects to function type (sum and max) as parameters of "default" and "const" of the example, and then, when speaking of sub_parsers, also puts a function as "default" - but the Parser object does not calls these functions directly: what calls the function is to do something like

# isso cria um "paramtro escondido" "func" no subparser,
# com o valor sendo a função "foo":
parser_foo.set_defaults(func=foo)

...
# isso pega o objeto Python guardado no parâmetro "escondido"
# e usa esse parâmetro como uma função:

args.func(args)

I think this approach is a little too esoteric, and a little too witty: if using parseargs, prefer to use "if"pure and simple: it’s easy understand what you’re doing.

If you’d rather streamline calling multiple functions, you’d better use a cleaner argument lib than Argparse, such as click: yes, it lets you mark functions with decorators, which can then be automatically called with command line options.

  • Thanks, it helped a lot, but really crazy documentation, I will end up using Click kkk

Browser other questions tagged

You are not signed in. Login or sign up in order to post.