Argument Parser

General Information

Create Python scripts that use short and long arguments.


  • Import argparse


Pass the “-h” or “–help” to view the built arguments -h

The Code
# 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 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...")
  print("Will NOT email results.")

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