The argparse module makes it really easy to read, parse and use the input arguments passed to a Python program.
Usage is in 3 simple steps:
- Create an object of
- Add the arguments you want to parse one by one using
- Parse the inputs and extract the arguments using
parse_args. The arguments are returned in an object with the values available using the object members.
Here is a simple program that illustrates usage of argparse with different types of input arguments:
This call has many useful options, the only one I actually use is:
description: Specify what you want to be displayed about this program when it is invoked using
This call has many useful options. Many of them are needed in most scripts:
- The first input is the option name. If the option is named without a single or double dash, as say
radius, then it becomes a positional argument. So, you cannot invoke its option name, but can directly pass its value. For example:
- An option can be specified with a single
-ror double dash
--radius. You can access the value of this option later in the argument object using
- An option can be specified with both single and double dashes, just separate both the quoted strings by a comma. Note that you can only access the value later using the name provided to the double dash option
- Input argument to a named option can be separated by a space
--radius 13or using the equals symbol
- action parameter: There are many strings that can be passed to this parameter indicating what to do when the option is invoked. The most typical usage is to set a True or False value for a boolean using
- default parameter: Specify the default value to be set if you do not provide a value for this option at the shell.
- type parameter: Specify what type the input value should be interpreted as. If you do not specify this, then it will be stored as a string. An error will be thrown if the input you provide cannot be converted to this type.
- required parameter: Set this to True if providing a value to this parameter is mandatory. An error is thrown at runtime if the value is not provided by user.
- help parameter: Set the string to shown as documentation when the program is invoked with
- dest parameter: Specify the member name to be used to store the value passed to this option. By default it has the same name as the option name. If the option name had dashes, they are converted to underscores to create a valid member name.
- When the program is invoked with
--help, it will list the input options available and the documentation you have provided for each option.
Tried with: Python 3.5 and Ubuntu 16.04