简体   繁体   中英

python argparse optional positional argument with detectable switch

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?

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM