Skip to content
Advertisement

Tag: argparse

Python argparse: Make at least one argument required

I’ve been using argparse for a Python program that can -process, -upload or both: The program is meaningless without at least one parameter. How can I configure argparse to force at least one parameter to be chosen? UPDATE: Following the comments: What’s the Pythonic way to parametrize a program with at least one option? Answer

Stop parsing on first unknown argument

Using argparse, is it possible to stop parsing arguments at the first unknown argument? I’ve found 2 almost solutions; parse_known_args, but this allows for known parameters to be detected after the first unknown argument. nargs=argparse.REMAINDER, but this won’t stop parsing until the first non-option argument. Any options preceding this that aren’t recognised generate an error. Have I overlooked something? Should

Get selected subcommand with argparse

When I use subcommands with python argparse, I can get the selected arguments. So args doesn’t contain ‘foo’. Simply writing sys.argv[1] doesn’t work because of the possible global args. How can I get the subcommand itself? Answer The very bottom of the Python docs on argparse sub-commands explains how to do this: You can also use the set_defaults() method referenced

Advertisement