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:
- Provide help argument for new user
- 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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| """ | |
| # Author: Raja David Hasugian | |
| # Using argparse to pass arguments into python script | |
| # Tutorial: https://techwithraja.wordpress.com/2017/05/10/memakai-argparse-untuk-memberikan-argumen-pada-skrip-python-2/ | |
| # June 2017 | |
| """ | |
| import argparse | |
| def process_argument(): | |
| # Create argument parser | |
| parser = argparse.ArgumentParser(description=r"Script to expedite QA process with 2 functions as described below.") | |
| # Create sub parser for each function menus | |
| 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() | |
| # Get arguments on main program | |
| 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() |
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:
- https://pymotw.com/2/argparse/
- http://tricksntweaks.blogspot.co.id/2013/05/advance-argument-parsing-in-python.html
- https://mkaz.tech/python-argparse-cookbook.html
Subparsing concept:


Leave a reply to Raja David Cancel reply