KnowledgeHub
Questions
Tags
Users
Search
Alex Rivera
|
Logout
Edit Question
Title
Body
I'd like to have an argument to my program that has some required parameters along with some optional parameters. Something like this: [--print text [color [size]] so you could pass it any of these: mycommand --print hello mycommand --print hello blue mycommand --print hello red 12 There could be multiple of these so it has to be a single add_argument. For example: [--print text [color]] [--output filename [overwrite]] I can achieve arguments that are close to what I want: >>> parser = argparse.ArgumentParser() >>> act = parser.add_argument('--foo', nargs=3, metavar=('x','y','z')) >>> act = parser.add_argument('--bar', nargs='?') >>> act = parser.add_argument('--baz', nargs='*') >>> parser.print_help() usage: [-h] [--foo x y z] [--bar [BAR]] [--baz [BAZ [BAZ ...]]] optional arguments: -h, --help show this help message and exit --foo x y z --bar [BAR] --baz [BAZ [BAZ ...]] but not quite. Is there any way to do this with argparse? I know I could make them all nargs="*" but then --help would not list the names of the optional arguments. If I pass nargs="*" and a tuple for metavar, argparse throws an exception.
Tags (comma-separated)
Save Edits
Cancel