[Python] ignore argparse generated help and usage messages and issues errors when users give...

Discussão em 'Python' iniciado por Stack, Setembro 29, 2024.

  1. Stack

    Stack Membro Participativo

    Let s assume I have a parser:

    import argparse
    def int_main():
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
    help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
    const=sum, default=max,
    help='sum the integers (default: find the max)')

    args = parser.parse_args()
    print(args.accumulate(args.integers))
    return 1

    if __name__ == '__main__':
    int_main()


    Assuming the Python code above is saved into a file called prog.py. If I give it wrong arguments in the command line:

    python prog.py a b c



    It gives this error message:

    usage: prog.py [-h] [--sum] N [N ...]
    prog.py: error: argument N: invalid int value: 'a'


    In a context of mine, I don't want that error message to be generated, I want for example int_main() simply to return False if any error raised indicating parsing errors.

    How to do that?

    I tried :

    import argparse
    def int_main():
    parser = argparse.ArgumentParser(description='Process some integers.')
    parser.add_argument('integers', metavar='N', type=int, nargs='+',
    help='an integer for the accumulator')
    parser.add_argument('--sum', dest='accumulate', action='store_const',
    const=sum, default=max,
    help='sum the integers (default: find the max)')
    try:
    args = parser.parse_args()
    # print(args.accumulate(args.integers))
    except:
    return False
    return True

    if __name__ == '__main__':
    res = int_main()
    print(res)



    but didn't work.

    Continue reading...

Compartilhe esta Página