python_wiki:argument_parser

Differences

This shows you the differences between two versions of the page.

Link to this comparison view

python_wiki:argument_parser [2017/09/02 18:35]
billdozor created
python_wiki:argument_parser [2019/05/25 23:50]
Line 1: Line 1:
-====== 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> 
-#======================= 
-# 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)