argparse: identify which subparser was used [duplicate]

This question already has answers here: Get selected subcommand with argparse (3 answers) Closed 8 years ago. I think this must be easy but I do not get it. Assume I have the following arparse parser: import argparse parser = argparse.ArgumentParser( version=’pyargparsetest 1.0′ ) subparsers = parser.add_subparsers(help=’commands’) # all all_parser = subparsers.add_parser(‘all’, help=’process all apps’) … Read more

In Python, using argparse, allow only positive integers

The title pretty much summarizes what I’d like to have happen. Here is what I have, and while the program doesn’t blow up on a nonpositive integer, I want the user to be informed that a nonpositive integer is basically nonsense. import argparse parser = argparse.ArgumentParser() parser.add_argument(“-g”, “–games”, type=int, default=162, help=”The number of games to … Read more

Require either of two arguments using argparse

Given: import argparse pa = argparse.ArgumentParser() pa.add_argument(‘–foo’) pa.add_argument(‘–bar’) print pa.parse_args(‘–foo 1’.split()) how do I make at least one of “foo, bar” mandatory: –foo x, –bar y and –foo x –bar y are fine make at most one of “foo, bar” mandatory: –foo x or –bar y are fine, –foo x –bar y is not 2 … Read more

Python argparse ignore unrecognised arguments

Optparse, the old version just ignores all unrecognised arguments and carries on. In most situations, this isn’t ideal and was changed in argparse. But there are a few situations where you want to ignore any unrecognised arguments and parse the ones you’ve specified. For example: parser = argparse.ArgumentParser() parser.add_argument(‘–foo’, dest=”foo”) parser.parse_args() $python myscript.py –foo 1 … Read more

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: ./myprogram -h or: ./myprogram –help 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 … Read more