[Python Patterns] Using Argparse

This is just a simple pattern I use when I need a quick and dirty script.

I usually base most of my scripts on this.

Make sure you pip install argparse before using the script.

This just repeats an IP address back to you.

# argparse_example.py
import argparse
import sys

# Example usage
# python argparse_example.py -i

# Example output
# You entered this data:  {'ip_addr': ['']}

def main(**kwargs):
    """ argparse example """

    # String Formatting

    data = 'You entered this data:  {}'.format(kwargs)

    return print(data)

if __name__ == '__main__':

    parser = argparse.ArgumentParser()

    parser.add_argument('-i', nargs='+', dest='ip_addr',
                        help='Enter the ip address', required=False)

    args = parser.parse_args()

    # Convert the argparse.Namespace to a dictionary: vars(args)
    arg_dict = vars(args)
    # pass dictionary to main

My blog posts tagged with "Python Patterns" are designed to be a quick look reference for some Python code snippets I use a lot.  They are written to be a quick starting point for future projects so I do not need to type as much.