[[python_wiki:argument_parser]]

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

program-name.py -h

The Code

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.")

  • python_wiki/argument_parser.txt
  • Last modified: 2019/05/26 03:50
  • (external edit)