1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

[Python] Check if ArgParse optional argument is set, default value supplied

Discussão em 'Python' iniciado por Stack, Outubro 7, 2024 às 12:52.

  1. Stack

    Stack Membro Participativo

    I'm trying to check if an optional argument is supplied by the user but I want to set its default value if it is not supplied. If I try to use if statement by exploiting None, the default in help string says None which is incorrect

    import argparse
    parser = argparse.ArgumentParser(usage=__file__ + " [--options]",
    description=__doc__,
    formatter_class=argparse.ArgumentDefaultsHelpFormatter)

    parser.add_argument("--scheme", choices=["A", "B"])
    parser.add_argument("--min-A", type=float, help="Default=5")
    parser.add_argument("--min-B", type=float, help="Default=10")
    args = parser.parse_args()

    if args.scheme == "A":
    if args.min_A:
    min_A = args.min_A
    else:
    min_A = 5
    else:
    if args.min_A:
    parser.error("--min-A can only be provided when --scheme is A")

    #similar code for B


    Here, the help string automatically puts default as None. If I put default as 5, then I'm not able to check whether --min-A has been provided by user because it stores the default instead of None when the option is absent in input.

    Any ideas on how to execute this?

    Continue reading...

Compartilhe esta Página