如何使用argparse为参数设置可选值? [英] How to make an optional value for argument using argparse?

查看:48
本文介绍了如何使用argparse为参数设置可选值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个python脚本,我想在该脚本中使用一个参数来控制您获得多少搜索结果作为输出.我目前已将参数命名为--head.这是我想要的功能:

I am creating a python script where I want to have an argument that manipulates how many search results you get as output. I've currently named the argument --head. This is the functionality I'd like it to have:

  1. 当未在命令行中传递--head时,我希望它默认为一个值.在这种情况下,相当大的一个,例如80

  1. When --head is not passed at the command line I'd like it to default to one value. In this case, a rather big one, like 80

当传递--head不带任何值时,我希望它默认为另一个值.在这种情况下,有一些限制,例如10

When --head is passed without any value, I'd like it to default to another value. In this case, something limited, like 10

当使用值传递--head时,我希望它存储它传递的值.

When --head is passed with a value, I'd like it to store the value it was passed.

以下是描述问题的代码:

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.

推荐答案

在阅读了文档多一点之后,我发现了我需要的东西:nargs='?'. 这与store动作一起使用,并且完全符合我的要求.

After a little more reading in the documentation I found what I needed: nargs='?'. This is used with the store action, and does exactly what I want.

这里是一个例子:

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

来源: http://docs.python.org/3/library/argparse.html#nargs

这篇关于如何使用argparse为参数设置可选值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆