Argparse optional argument with different default if specified without a value

后端 未结 2 732
别跟我提以往
别跟我提以往 2020-12-21 12:06

Consider three different runs of a program:

python3 prog.py
python3 prog.py --x
python3 prog.py --x 2

Is it possible to use argparse<

2条回答
  •  粉色の甜心
    2020-12-21 12:39

    If you are happy to do a little post-processing, you can get it:

    sentinel = object()
    parser.add_argument('--x', nargs='?', type=int, default=sentinel)
    args = parser.parse_args()
    if args.x is sentinel:
        args.x = None
    elif args.x is None:
        args.x = 1
    

    However, it is bending the tool in a bit of a strange way. You may want to consider instead the count action, which is commonly used to specify verbosity levels, for example (-v, -vv, -vvv).

提交回复
热议问题