零个或一个参数
Zero or one argument
当参数可以是零个或一个参数时,我必须使用哪个操作?
我必须 运行 这样的代码,并将设置为默认值 4
(此变体退出时出现错误)
--pretty-xml
error: argument --pretty-xml: expected one argument
但我也可以运行这样编码
--pretty-xml = 2
我的代码是这样的
parameter.add_argument('--pretty-xml', dest="pretty", action="append", default=[4])
两个选项参数需要更改什么?
谢谢
您需要将 nargs
参数与 ?
以及 default
和 const
参数一起使用:
'?'
. 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, const=5, nargs='?', type=int)
如果像 --pretty-xml=n
那样调用,这将具有值 n
,如果像 --pretty-xml
那样调用,则值为 5
或如果 --pretty-xml
不存在,则值为 4完全在命令行上。
注意:使用type=int
检查类型并转换为int类型。否则 returns string 如果指定了参数,returns int 4 如果没有指定参数。
当参数可以是零个或一个参数时,我必须使用哪个操作? 我必须 运行 这样的代码,并将设置为默认值 4 (此变体退出时出现错误)
--pretty-xml
error: argument --pretty-xml: expected one argument
但我也可以运行这样编码
--pretty-xml = 2
我的代码是这样的
parameter.add_argument('--pretty-xml', dest="pretty", action="append", default=[4])
两个选项参数需要更改什么? 谢谢
您需要将 nargs
参数与 ?
以及 default
和 const
参数一起使用:
'?'
. 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, const=5, nargs='?', type=int)
如果像 --pretty-xml=n
那样调用,这将具有值 n
,如果像 --pretty-xml
那样调用,则值为 5
或如果 --pretty-xml
不存在,则值为 4完全在命令行上。
注意:使用type=int
检查类型并转换为int类型。否则 returns string 如果指定了参数,returns int 4 如果没有指定参数。