# Demnstrate how to handle options, especially command line options # # Matt Bishop, MHI 289I, Fall 2025 # import getopt import sys # # first, using just strings # # idea: options are # -a # -b # -c something # -d something # anything else is an argument # args = ['-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2'] print("Argument list:", args) optlist, arglist = getopt.getopt(args, 'abc:d:') print("The options and their arguments are:\n\t", optlist) print("The arguments to the command are:\n\t", arglist) # # now let's introduce an error: # same thing but with -x: # print("\nNow introducing '-x' as an option, but not including it in getopt") args = [ '-x', '-a', '-b', '-d', 'bar', 'a1', 'a2'] print("Argument list:", args) try: optlist, arglist = getopt.getopt(args, 'abc:d:') except getopt.GetoptError as msg: print("Option error:", msg) print("The options and their arguments are:\n\t", optlist) print("The arguments to the command are:\n\t", arglist) # # now let's introduce an error: # same thing but with -x *and* -y: # print("\nNow using '-x' and '-y' as options, but not including them in getopt") args = [ '-x', '-y', '-a', '-b', '-cfoo', '-d', 'bar', 'a1', 'a2'] print("Argument list:", args) try: optlist, arglist = getopt.getopt(args, 'abc:d:') except getopt.GetoptError as msg: print("Option error:", msg) print("The options and their arguments are:\n\t", optlist) print("The arguments to the command are:\n\t", arglist) print("Note the '-y' option is silently ignored") # # now define them from the environment # print("\nNow from the command line:") print("Argument list:", sys.argv[1:]) try: optlist, arglist = getopt.getopt(sys.argv[1:], 'abc:d:') except getopt.GetoptError as msg: print("Option error:", msg) print("The options and their arguments are:\n\t", optlist) print("The arguments to the command are:\n\t", arglist)