getopt: Make argument mandatory

Frans Englich frans.englich at telia.com
Wed Dec 15 08:59:10 EST 2004


Hello,

In my use of getopt.getopt, I would like to make a certain parameter 
mandatory. I know how to specify such that a parameter must have a value if 
it's specified, but I also want to make the parameter itself 
mandatory(combined with a mandatory value, the result is that the user must 
specify a value).

Here's code illustrating my point(see the TODO):

    # Parse command line flags
    # --------------------------------------------
    configurationFile = ""
    try:

        opts, args = getopt.getopt( argv, "hVc:", ["help", "version",
        "configuration-file="])
        for opt,arg in opts:
            if opt in ("-c", "--configuration-file"):
                configurationFile = arg

            if opt in ("-h", "--help"):
                usage()

            if opt in ("-V", "--version"):
                print "Version:", common.version["Runner"]
                sys.exit()

        # TODO Can't getopt make an argument mandatory?
        if configurationFile == "":
            print "You must pass an URL/path to a configuration file, see 
--help."
            sys.exit(common.exitCodes["parameter"])

    except getopt.GetoptError:
        usage()
    # --------------------------------------------


Is it possible?


Cheers,

		Frans




More information about the Python-list mailing list