Last active
February 2, 2022 02:34
-
-
Save rajadavidh/45561edd8cd4d328acce1d92d2bc22f4 to your computer and use it in GitHub Desktop.
Using argparse to pass arguments into python script
This file contains 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() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment