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
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:
- http://stackoverflow.com/questions/4575747/get-selected-subcommand-with-argparse
- http://stackoverflow.com/questions/8250010/argparse-identify-which-subparser-was-used
- http://www.prschmid.com/2013/07/parsing-arguments-in-python-with.html
- http://tylerturk.com/argparse-with-custom-subparsing/
Which font have you used in the command line? It’s so beautiful!
Do let me know; I would like to set my terminal to the same as well.
Hi @Hoodafukisalice,
Thanks for the comment. I use Monaco typeface for my terminal.
Many thanks Raja