python argparse optional positional argument with

2019-08-03 01:57发布

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

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?

1条回答
你好瞎i
2楼-- · 2019-08-03 02:48

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

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.

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)
查看更多
登录 后发表回答