Print program usage example with argparse module

Use parser.epilog to display something after the generated -h text. parser = argparse.ArgumentParser( description=’My first argparse attempt’, epilog=’Example of use’) output = parser.parse_args() prints: My first argparse attempt optional arguments: -h, –help show this help message and exit Example of use

Conditional command line arguments in Python using argparse

The argparse module offers a way to do this without implementing your own requiredness checks. The example below uses “subparsers” or “sub commands”. I’ve implemented a subparser for “dump” and one for “format”. import argparse parser = argparse.ArgumentParser() parser.add_argument(‘file’, help=’The file you want to act on.’) subparsers = parser.add_subparsers(dest=”subcommand”) subparsers.required = True # required since … Read more

Call function based on argparse

Since it seems like you want to run one, and only one, function depending on the arguments given, I would suggest you use a mandatory positional argument ./prog command, instead of optional arguments (./prog –command1 or ./prog –command2). so, something like this should do it: FUNCTION_MAP = {‘top20’ : my_top20_func, ‘listapps’ : my_listapps_func } parser.add_argument(‘command’, … Read more

SystemExit: 2 error when calling parse_args() within ipython

argparse is a module designed to parse the arguments passed from the command line, so for example if you type the following at a command prompt: $ python my_programme.py –arg1=5 –arg2=7 You can use argparse to interpret the –arg1=5 –arg2=7 part. If argparse thinks the arguments are invalid, it exits, which in general is done … Read more

Default sub-command, or handling no sub-command with argparse

On Python 3.2 (and 2.7) you will get that error, but not on 3.3 and 3.4 (no response). Therefore on 3.3/3.4 you could test for parsed_args to be an empty Namespace. A more general solution is to add a method set_default_subparser() (taken from the ruamel.std.argparse package) and call that method just before parse_args(): import argparse … Read more

Print command line arguments with argparse?

ArgumentParser.parse_args by default takes the arguments simply from sys.argv. So if you don’t change that behavior (by passing in something else to parse_args), you can simply print sys.argv to get all arguments passed to the Python script: import sys print(sys.argv) Alternatively, you could also just print the namespace that parse_args returns; that way you get … Read more

How can I require my python script’s argument to be a float in a range using argparse?

The type parameter to add_argument just needs to be a callable object that takes a string and returns a converted value. You can write a wrapper around float that checks its value and raises an error if it is out of range. def restricted_float(x): try: x = float(x) except ValueError: raise argparse.ArgumentTypeError(“%r not a floating-point … Read more