Argparse optional argument with different default if specified without a value

后端 未结 2 731
别跟我提以往
别跟我提以往 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:55

    nargs'?' with a const parameter handles this 3-way input nicely..

    In [2]: parser = argparse.ArgumentParser()
    In [3]: parser.add_argument('-x','--x', nargs='?', type=int, const=1)
    ...
    In [4]: parser.parse_args([])
    Out[4]: Namespace(x=None)
    In [5]: parser.parse_args(['-x'])
    Out[5]: Namespace(x=1)
    In [6]: parser.parse_args(['-x','2'])
    Out[6]: Namespace(x=2)
    

    I could have also given it a default parameter.

    how to add multiple argument options in python using argparse?

提交回复
热议问题