Show pageOld revisionsBacklinksBack to top This page is read only. You can view the source, but not change it. Ask your administrator if you think this is wrong. ====== Argument Parser ====== **General Information** Create Python scripts that use short and long arguments. **Checklist** * Import argparse ---- ====== Usage ====== Pass the "-h" or "--help" to view the built arguments <code bash> program-name.py -h </code> ---- ====== The Code ====== <code python program-name.py> #!/usr/bin/python #======================= # Import Modules #======================= # argparse: Command line arguments import argparse #======================= # Get Script Arguments #======================= # Build argument parser information parser = argparse.ArgumentParser(description="Put a good program description here.") parser.add_argument("-n","--name", help="This is your name.", required=True) parser.add_argument("-e","--email", help="Email results.", action="store_true", required=False) parser.add_argument("-t","--test", help="Do not make changes; perform a test and output details of what would happen.", action="store_true", required=False) args = vars(parser.parse_args()) # If testing, we don't actually want to do anything if args['test'] == True: print("-->> Test run...no modifications will be made <<--") #- Using stored variables from arguments -# # Since name is required, program will not run without providing it print("Your name is: " + args['name']) if args['email'] == True: print("Emailing results...") else: print("Will NOT email results.") </code> ---- python_wiki/argument_parser.txt Last modified: 2019/05/25 23:50(external edit)