python tutorial - Python Argparse - learn python - python programming
What is Argparse?
- The Argparse module makes it easy to write user-friendly command-line interfaces.
- The program defines what arguments it requires, and Argparse will figure out how to parse those out of sys.argv.
- The Argparse module also automatically generates help and usage messages and issues errors when users give the program invalid arguments." - from Argparse - Parser for command-line options, arguments and sub-commands
The following description is from The Argparse module is now part of the Python standard library!
- The Argparse module provides an easy, declarative interface for creating command line tools, which knows how to:
- parse the arguments and flags from sys.argv
- convert arg strings into objects for your program
- format and print informative help messages
- The Argparse module improves on the standard library optparse module in a number of ways including:
- handling positional arguments
- supporting sub-commands
- allowing alternative option prefixes like + and /
- handling zero-or-more and one-or-more style arguments
- producing more informative usage messages
- providing a much simpler interface for custom types and actions
A simple sample
Let's look at our first sample of using Argparse:
If we run it:
Note that the 'host' arg is set as 'required'. So, if we run the code without feeding host ip, we'll get an error like this:
Also, we need to look at how the help works:
Notice that we used -H for host-ip mandatory option instead of lower case 'h' because it is reserved for 'help.
Another sample code:
Just to see how it works, let's request 'help':
We need to check the add_argument() method in ArgumentParser.add_argument():
1.name or flags - Either a name or a list of option strings, e.g. foo or -f, --foo.
2.action - The basic type of action to be taken when this argument is encountered at the command line.
3.nargs - The number of command-line arguments that should be consumed.
4.const - A constant value required by some action and nargs selections.
5.default - The value produced if the argument is absent from the command line.
6.type - The type to which the command-line argument should be converted.
7.choices - A container of the allowable values for the argument.
8.required - Whether or not the command-line option may be omitted (optionals only).
9.help - A brief description of what the argument does.
10.metavar - A name for the argument in usage messages.
11.dest - The name of the attribute to be added to the object returned by parse_args().
- Now, it's time to run the code:
- The '+' in nargs='+', just like '*', makes all command-line args present to be gathered into a list.
- If we provide a wrong type arg such as a float type, we'll get an error: