Python argparse: default value or specified value

后端 未结 3 808
我寻月下人不归
我寻月下人不归 2020-11-27 10:27

I would like to have a optional argument that will default to a value if only the flag is present with no value specified, but store a user-specified value instead of the de

相关标签:
3条回答
  • 2020-11-27 11:11

    Actually, you only need to use the default argument to add_argument as in this test.py script:

    import argparse
    
    if __name__ == '__main__':
    
        parser = argparse.ArgumentParser()
        parser.add_argument('--example', default=1)
        args = parser.parse_args()
        print(args.example)
    

    test.py --example
    % 1
    test.py --example 2
    % 2
    

    Details are here.

    0 讨论(0)
  • 2020-11-27 11:13

    The difference between:

    parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1, default=7)
    

    and

    parser.add_argument("--debug", help="Debug", nargs='?', type=int, const=1)
    

    is thus:

    myscript.py => debug is 7 (from default) in the first case and "None" in the second

    myscript.py --debug => debug is 1 in each case

    myscript.py --debug 2 => debug is 2 in each case

    0 讨论(0)
  • 2020-11-27 11:18
    import argparse
    parser = argparse.ArgumentParser()
    parser.add_argument('--example', nargs='?', const=1, type=int)
    args = parser.parse_args()
    print(args)
    

    % test.py 
    Namespace(example=None)
    % test.py --example
    Namespace(example=1)
    % test.py --example 2
    Namespace(example=2)
    

    • nargs='?' means 0-or-1 arguments
    • const=1 sets the default when there are 0 arguments
    • type=int converts the argument to int

    If you want test.py to set example to 1 even if no --example is specified, then include default=1. That is, with

    parser.add_argument('--example', nargs='?', const=1, type=int, default=1)
    

    then

    % test.py 
    Namespace(example=1)
    
    0 讨论(0)
提交回复
热议问题