Python Command Line Processor

I write a lot of my research code in Python these days. Compared to C, C++, or Java, it is a joy to work in. However, I found myself writing the same code again and again to validate command line arguments.

Not content with argparse, I have written my own command line parsing module.

The source can be found on Bitbucket.

The processor allows a program to register a set of command line arguments, which may be required or not, and may come with a default value and a description. The program builds a help menu which can be displayed by using the --help flag. Its output can be suppressed with the --quiet flag.

The code is free to use (with attribution) and bug fixes and feature submission on Bitbucket will be appreciated.

A simple string argument is added as follows:

arg_processor = ArgProcessor() 
arg_processor.add_program_arg('-req_str_arg', #The arg string
    ArgDefinition('required_string_argument', #The variable of the arg
        True, #If the arg is required
        None, #The validator, if any
        None, #The args to the validator
        None, #The default value for non required args
        "A required string arg with no validator" # A description

The processor also comes with a set of built in argument validators, which validate arguments. It is also possible to easily write and register new validators with the system.

Here are some example arguments using validators:

        [float, 0, 1, False, "Error - invalid floating point argument: "],
        "An required float arg with a lower bound of 0, an upper bound of 1, which cannot take the value None"
        [['value1', 'value2', 'value3'], "Error - invalid opt_enum_arg value: "],
        "An optional enumerated argument with three values"

Finally, it is possible to add flags and check if they were supplied. Optionally, flags can be supplied with a function which is called after arguments have been passed. Here is an example:

        "Display citation information"

Leave a Reply