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