带有可检测开关的python argparse可选位置参数 [英] python argparse optional positional argument with detectable switch
问题描述
我想像 program -s
一样调用我的程序.我想分配一个默认值,但也希望能够检测是否给出了 -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
和 None
,这给我一个 args.s
的值如果我指定 -s
没有值.我想要的是 args.s
等于 None
如果没有给出开关,并且 args.s
设置为带有 的默认值-s
给定,并且 args.s
等于 custom_value
如果作为 program -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
因为我假设您想将输入视为 int.
Additionally, I added a type=int
because I assumed that you want to treat the input as an int.
因此,您的代码应该是:
So, your code should be:
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屋!