[Python] Problems with Python argparse library (order of variables, default parameters and so...

Discussão em 'Python' iniciado por Stack, Abril 6, 2025.

  1. Stack

    Stack Membro Participativo

    I want to give my script named console parameters in any order, but my code won't work as it should.

    import argparse, sys

    parser = argparse.ArgumentParser()
    parser.add_argument('n', help="some integer which is needed", type=int, default=100)
    parser.add_argument('b', help="a yes or no question (default yes)", type=str, default=True)
    args=parser.parse_args()
    print(args)


    I want to be able to do all of the following things which are all failing in their own unique annoying ways:

    • python myscript.py n=85
    • python myscript.py b=No
    • python myscript.py b=No n=47

    all result in an invalid int error and it is driving me up the wall. Why can't I just tell the script what n and b are in the order I like? Why can't I give the value of a parameter with its name? Why are my default values totally ignored? Also python myscript.py 7458 b=yes

    is also not much better it prints Namespace(n=7458, b='b=yes')

    so why can't I say something like n=7458, why is b= not understood to be not part of the b value?

    Continue reading...

Compartilhe esta Página