Programming, Teknologi

Using argparse to pass arguments into python script

Artikel ini juga tersedia dalam terjemahan Bahasa indonesia dengan judul Memakai argparse untuk memberikan argumen pada skrip python.

While doing some QA tasks, I got a case which I need to add and delete domain names from hundreds of categorized text files time after time.

Since it was repetitive and cost me time to perform it, I decided to create python script for automating that case.

Inspired by simplicity of linux command: ls which has several arguments with distinct functionalities, I also want my python script to be able to run multiple functions.

To accommodate that, I need to separate the input arguments.

After doing internet research, I found argparse solving this issue. With argparse library, user can pass arguments into python script.

Let’s write this argparse script.

What the program does:

  1. Provide help argument for new user
  2. Receive arguments for particular functions: add and delete domain name

Step 1: Create argument parser

Create a python file and save it as argparse_example.py

import argparse

def process_argument():
    parser = argparse.ArgumentParser(description=r"Script to expedite QA process with 2 functions as described below.")

# TODO : Create sub parser for each function menus

# TODO : Get arguments on main program

TODO comments are just skeleton for the program.

Step 2: Create subparser for each function menus

import argparse

def process_argument():
    parser = argparse.ArgumentParser(description=r"Script to expedite QA process with 2 functions as described below.")

    subparsers = parser.add_subparsers(dest='options', help='choose script action')

    add_parser = subparsers.add_parser('add', help='adding domains to destination category')
    add_parser.add_argument('-n', '--domain_name', action='store', help='Store a domain value')
    add_parser.add_argument('-d', '--destination_category', action='store', help='file path of destination domain')

    delete_parser = subparsers.add_parser('delete', help='deleting domains from source category')
    delete_parser.add_argument('-n', '--domain_name', action='store', help='Store a domain value')
    delete_parser.add_argument('-s', '--source_category', action='store', help='file path of source domain')

    try:
        return parser.parse_args()
    except IOError, msg:
        parser.error(str(msg))

# TODO : Get arguments on main program

Each subparser has its own input arguments with functionality description.

Step 3: Get arguments on main program

import argparse

def process_argument():
    parser = argparse.ArgumentParser(description=r"Script to expedite QA process with 2 functions as described below.")

    subparsers = parser.add_subparsers(dest='options', help='choose script action')

    add_parser = subparsers.add_parser('add', help='adding domains to destination category')
    add_parser.add_argument('-n', '--domain_name', action='store', help='Store a domain value')
    add_parser.add_argument('-d', '--destination_category', action='store', help='file path of destination domain')

    delete_parser = subparsers.add_parser('delete', help='deleting domains from source category')
    delete_parser.add_argument('-n', '--domain_name', action='store', help='Store a domain value')
    delete_parser.add_argument('-s', '--source_category', action='store', help='file path of source domain')

    try:
        return parser.parse_args()
    except IOError, msg:
        parser.error(str(msg))

def main():
    args = process_argument()

    if args.options == 'delete':
        print 'Deleting ' + args.domain_name + ' from ' + args.source_category + ' is succeeded.'
    elif args.options == 'add':
        print 'Adding ' + args.domain_name + ' on ' + args.destination_category + ' is succeeded.'

if __name__ == "__main__":
    main()

Adding the feedback on main program to notify user that the argument is working as expected.

Final result

Running program

Perform global help function: python argparse_example.py -h

Perform help for each function

Add: python argparse_example.py add -h

Delete: python argparse_example.py delete -h

Perform add domain name function: python argparse_example.py add -n testing.com -d someCategory

Perform delete domain name function: python argparse_example.py delete -n testing.com -s someCategory

Further reading

Basic concept:

Subparsing concept:

Advertisements
Standard

One thought on “Using argparse to pass arguments into python script

  1. Pingback: Memakai argparse untuk memberikan argumen pada skrip python | Raja David's Journal

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s