零或一个参数

时间:2017-04-09 23:09:04

标签: python argparse

当参数可以为零或一个参数时,我必须使用哪个动作? 我必须运行这样的代码,并将设置默认值4 (此变体退出并出错)

--pretty-xml
error: argument --pretty-xml: expected one argument

但是我可以运行这样的代码

--pretty-xml = 2 

我的代码看起来像这样

parameter.add_argument('--pretty-xml',  dest="pretty", action="append", default=[4])

需要更改什么才能适用于两个选项参数? 感谢

1 个答案:

答案 0 :(得分:3)

You need to use nargs argument with ?:

'?'. One argument will be consumed from the command line if possible, and produced as a single item. If no command-line argument is present, the value from default will be produced. ...


parser.add_argument('--pretty-xml', dest='pretty', default=4, nargs='?', type=int)

NOTE: used type=int to check type and convert to int type. Otherwise returns string if the argument is specified, returns int 4 if no argument is specified.