Tuesday, March 02, 2010

March Madness Challenge - Day 2

Ok. Time was a bit of challenge today. I wanted to learn more about getopt, and figure out how it differed from optparse. I definitely learned about some of those differences. So tonights program uses getpass to collect a username, password combination. This is pretty unoriginal, but it did help me learn about getopt. I would like to try variation on determining mandatory fields, optional fields, and fields in combination.


#
# Hello World Get Opt for Python
#
#
import getopt
import sys
import getpass

#Describe usage
def usage():
print "-h, --help\n -v, --verbose\n -u, --username\n -p, --password\n"

def main():
try:
opts, args = getopt.getopt(sys.argv[1:], "h:u:pv", ["help", "username=", "password"])
except getopt.GetoptError, err:
#print help information and exit:
print str(err) # will print something like "option -a not recognized"
usage()
sys.exit(2)
username = None
password = None
verbose = False

for o, a in opts:
if o == "-v":
verbose = True
elif o in ("-h", "--help"):
usage()
sys.exit()
elif o in ("-u", "--username"):
username = a
print "username: " + username
elif o in ("-p", "--password"):
password = getpass.getpass("Enter password: ")
print "password: " + password
else:
assert False, "unhandled option"

if __name__ == "__main__":
main()

No comments: