I’m writing a program in which I would like to have arguments like this: Is there a way to get argparse to do this for me? Answer v3.9 has added an action class that does this. From the docs (near the end of the action section) The BooleanOptionalAction is available in argparse and adds support for boolean actions such as
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
Display help message with Python argparse when script is called without any arguments
Assume I have a program that uses argparse to process command line arguments/options. The following will print the ‘help’ message: or: But, if I run the script without any arguments whatsoever, it doesn’t do anything. What I want it to do is to display the usage message when it is called with no arguments. How is that done? Answer This