[英]How to make an optional value for argument using argparse?
I am creating a python script where I want to have an argument that manipulates how many search results you get as output. 我正在创建一个python脚本,我希望有一个参数来操作你输出的搜索结果数量。 I've currently named the argument
--head
. 我目前已将参数命名为
--head
。 This is the functionality I'd like it to have: 这是我希望它拥有的功能:
When --head
is not passed at the command line I'd like it to default to one value. 当
--head
没有在命令行传递时,我希望它默认为一个值。 In this case, a rather big one, like 80 在这种情况下,一个相当大的,像80
When --head
is passed without any value, I'd like it to default to another value. 当
--head
没有任何值传递时,我希望它默认为另一个值。 In this case, something limited, like 10 在这种情况下,有限的东西,如10
When --head
is passed with a value, I'd like it to store the value it was passed. 当
--head
传递一个值时,我希望它存储它传递的值。
Here is some code describing the problem: 以下是一些描述问题的代码:
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('-h',
'--head',
dest='size',
const=80,
default=10,
action="I don't know",
help='Only print the head of the output')
>>> # OFC, that last line will fail because the action is uknown,
... # but here is how I'd like it to work
... parser.parse_args(''.split())
Namespace(size=80)
>>> parser.parse_args('--head'.split())
Namespace(size=10)
>>> parser.parse_args('--head 15'.split())
Namespace(size=15)
I know I probably can write a custom action for this, but I first want to see if there is any default behaviour that does this. 我知道我可能会为此编写自定义操作,但我首先想看看是否有任何默认行为。
After a little more reading in the documentation I found what I needed: nargs='?'
在文档中
nargs='?'
我找到了我需要的东西: nargs='?'
. 。 This is used with the
store
action, and does exactly what I want. 这与
store
行为一起使用,完全符合我的要求。
Here is an example: 这是一个例子:
>>> import argparse
>>> parser = argparse.ArgumentParser()
>>> parser.add_argument('--head',
dest='size',
const=10,
default=80,
action='store',
nargs='?',
type=int,
help='Only print the head of the output')
>>> parser.parse_args(''.split())
... Namespace(size=80)
>>> parser.parse_args('--head'.split())
... Namespace(size=10)
>>> parser.parse_args('--head 15'.split())
... Namespace(size=15)
Source: http://docs.python.org/3/library/argparse.html#nargs 资料来源: http : //docs.python.org/3/library/argparse.html#nargs
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.