问题描述
我想调用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:
此外,我添加了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可选位置参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!