Argparse optional argument with different default if specified without a value

孤街浪徒 提交于 2019-12-11 09:52:15

问题


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 such that, for example, in the first case, x==None, in the second case, x==1, and in the third, x==2?


回答1:


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?




回答2:


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).



来源:https://stackoverflow.com/questions/48412407/argparse-optional-argument-with-different-default-if-specified-without-a-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!