"""Example of parsing command line arguments. LICENSE AGREEMENT The Original Code is "pyhelp.py". The Initial Developer of the Original Code is Leica Geosystems. Portions created by Leica Geosystems are Copyright (C) 2014 year. Leica Geosystems. All Rights Reserved. """ import sys import webbrowser import getopt SHORT_OPTIONS = "hv:" # v takes an argument, hence ":" LONG_OPTIONS = ["help", "version="] HELP_OPTIONS = ["-h", "--help"] VERSION_OPTIONS = ["-v", "--version"] USAGE = """ Usage: pyhelp.py [--version version] [--help] search-string" Parameter: search-string List of search terms that you wish to search. Options: --version (-v) Indicates what library you want to search in, values are 2.1, 2.2, 2.3 or current. --help (-h) Displays this message. Examples: pyhelp.py re pyhelp.py getopt pyhelp.py -v 2.2 getopt """ # This dictionary will hold our user options. Start by defining the # defaults, if the user defines something else, we will override the # default. OPTIONS = {"--version":"2.2", # default to 2.2 library "--help":0} # 0 no help; 1 show help def parse_command_line(): """Returns the options dictionary and parameters. Generates getopt.GetoptError if it can not process the command line. """ opts, params = getopt.getopt(sys.argv[1:], SHORT_OPTIONS, LONG_OPTIONS) # get the defaults options = OPTIONS.copy() for option, argument in opts: if option in HELP_OPTIONS: options["--help"] = 1 if option in VERSION_OPTIONS: options["--version"] = argument return options, params def make_url(version, searchterms): """Returns a URL based on the version and search terms.""" url = "http://starship.python.net/crew/theller/pyhelp.cgi" url += "?keyword=" + reduce(lambda x, y: x+"+"+y, searchterms) url += "&version" + version return url if __name__=="__main__": try: options, params = parse_command_line() except getopt.GetoptError, e: print "error: " + str(e) print USAGE sys.exit(-1) if options["--help"]==1: print USAGE sys.exit() if not params: print "error: search parameters required." sys.exit(-2) url = make_url(options["--version"], params) webbrowser.open_new(url)