Module - argparse

Python module: argparse #

Module to specify arguments from the command line when running Python scripts.

Module #

import argparse

Setting up the parser #

Container to hold the arguments.


# Set up the parser
parser = argparse.ArgumentParser(description = '<some descriptive text>')


# Then add arguments
# these are positional arguments, where order in call of script matters.

parser.add_argument('<argument1>', type = <int, str, etc>, help = '<descriptive text for how to use the argument>')

parser.add_argument('<argument2>', type = <int, str, etc>, help = '<descriptive text for how to use the argument>')

# Then parse the arguments
args = parser.parse_args()

Using the arguments #

Now that the arguments have been loaded and parsed, now we define how to use the arguments.

def some_function(args.<argument1>, args.<argument2>):
    """
    This function should have logic that uses the argument(s)
    """
    ...

From the command line #

Assuming the argparse module hsa been properly loaded and coded into the script.

> python3 <script>.py <argument1> <argument2>

To get help:

python3 <script>.py -h

Example #

A complete example:

import argparse

parser = argparse.ArgumentParser(description = "just add two numbers together")

parser.add_argument('first_num', type = float, help = 'first number')

parser.add_argument('second_num', type = float, help = 'second number')

args = parser.parse_args()

def add_two_nums(first_num, second_num):
    sum = first_num + second_num

    return sum

if __name__ == '__main__':
    print add_two_nums(args.first_num, args.second_num)

Optional arguments #

An alternative to positional arguments are optional arguments. These are implemented by adding a double dash before the argument name.

parser.add_argument('--<argument1>', type = '<int, str, etc>', help = '<descriptive text for how to use the argument>')

parser.add_argument('--<argument2>', type = '<int, str, etc>', help = '<descriptive text for how to use the argument>')

Can also add a shortened notation for the argument with a single dash.

parser.add_argument('-a', '--<argument1>', type = '<int, str, etc>', help = '<descriptive text for how to use the argument>')

parser.add_argument('-b','--<argument2>', type = '<int, str, etc>', help = '<descriptive text for how to use the argument>')

To call, specificy argument name or shortened notation.

> python3 <script>.py -a <argument1> -b <argument2>

or switch orders:

> python3 <script>.py -b <argument2> -a <argument1> 

When using optional arguments, if no argument is specified, they get populated with None.

Arguments can be made required with a required=True parameter.

parser.add_argument('-a', '--<argument1>', type = '<int, str, etc>', required=True, help = '<descriptive text for how to use the argument>')

parser.add_argument('-b','--<argument2>', type = '<int, str, etc>', required=True, help = '<descriptive text for how to use the argument>')

Mutually exclusive arguments #

action="store_true" – argument defaults to False, but when called, it becomes True.

group = parser.add_mutually_exclusive_group()
group.add_argument('-q', '--quiet', action="store_true", help = 'print quiet')
group.add_argument('-v', '--verbose', action="store_true", help = 'print verbose')

Then use conditionally:

...

if __name__ == '__main__':
    variable = some_function(args.<argument1>, args.<argument2>)
    if args.quiet:
        print variable
    elif args.verbone:
        print "Some string"
    elif:
        print "some other string"