带有可检测开关的python argparse可选位置参数 [英] python argparse optional positional argument with detectable switch

查看:96
本文介绍了带有可检测开关的python argparse可选位置参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想调用program -s <optional value>这样的程序.我想分配一个默认值,但也希望能够检测是否给出了-s开关. 我所拥有的:

I would like to invoce my programm like program -s <optional value>. I would like to assign a default value, but would also like to be able to detect if the -s switch was given. What I have:

max_entries_shown = 10
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-s",
    nargs = '?',
    default = max_entries_shown)
args = parser.parse_args()

如果我没有在命令行上给出-s,那么给我args.s的值是10,如果我没有指定值的-s则给None.如果没有开关,我想要的是args.s等于None,并且在给定-s的情况下将args.s设置为默认值,如果以program -s custom_value运行,则args.s等于custom_value.我该如何实现?

This gives me a value of 10 for args.s if I don't give -s on the command line, and None if I specify -s without a value. What I want is args.s equal to None if no switch is given, and args.s set to the default value with -s given, and args.s equal to custom_value if run as program -s custom_value. How can I achive this?

推荐答案

您必须使用const而不是default.引用argparse Python Docs中有关何时使用 const 的提示:

You have to use const instead of default. Quote from argparse Python Docs about when to use const:

使用选项字符串(如-f或--foo)和nargs ='?'调用add_argument()时.这将创建一个可选参数,后跟零个或一个命令行参数.解析命令行时,如果遇到选项字符串后没有命令行参数,则将使用const的值.有关示例,请参见nargs描述.

When add_argument() is called with option strings (like -f or --foo) and nargs='?'. This creates an optional argument that can be followed by zero or one command-line arguments. When parsing the command line, if the option string is encountered with no command-line argument following it, the value of const will be assumed instead. See the nargs description for examples.

此外,我添加了type=int,因为我假设您想将输入视为整数.

Additionally, I added a type=int because I assumed that you want to treat the input as an int.

因此,您的代码应为:

max_entries_shown = 10
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("-s",
    nargs = '?',
    const = max_entries_shown,
    type=int)
args = parser.parse_args()

此代码返回(带有打印参数)

This code returns (with print args)

$ python parse.py
Namespace(s=None)
$ python parse.py -s
Namespace(s=10)
$ python parse.py -s 12
Namespace(s=12)

这篇关于带有可检测开关的python argparse可选位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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