Mark Roddy's solution will work, but it requires modification of the attribute of the parser object at runtime and does not support alternative formatting options other than - or -. A less attractive solution is to modify the sys.argv array before running optparse and insert an empty string ("") after the switch, for which there is no need to have arguments. The only limitation of this method is that you have your own default options for a predicted value other than the one you insert in sys.argv (I chose None for the example below, but it really doesn't matter).
The following code creates an example parser and a set of parameters, extracts an array of allowed keys from the parser (using a little instance of the magic variable), and then iterates through sys.argv and each time it finds an allowed switch, it checks if it is not specified any arguments. If there is no argument after the switch, an empty line will be inserted into the line command. After changing sys.argv, the parser is called, and you can check the parameters whose values ββare "" and act accordingly.
#Instantiate the parser, and add some options; set the options' default values to None, or something predictable that #can be checked later. PARSER_DEFAULTVAL = None parser = OptionParser(usage="%prog -[MODE] INPUT [options]") #This method doesn't work if interspersed switches and arguments are allowed. parser.allow_interspersed_args = False parser.add_option("-d", "--delete", action="store", type="string", dest="to_delete", default=PARSER_DEFAULTVAL) parser.add_option("-a", "--add", action="store", type="string", dest="to_add", default=PARSER_DEFAULTVAL)
Zac b source share