Mark Roddys Lösung würde funktionieren, aber es erfordert Attributänderung eines Parser-Objekts während der Laufzeit und hat keine Unterstützung für andere alternative Formatierungen als - oder -. Eine etwas weniger aufwendige Lösung besteht darin, das sys.argv-Array vor dem Ausführen von optparse zu modifizieren und eine leere Zeichenfolge ("") nach einem Schalter einzufügen, der keine Argumente benötigt. Die einzige Einschränkung dieser Methode besteht darin, dass Sie für Ihre Optionen standardmäßig einen anderen vorhersehbaren Wert haben als den, den Sie in sys.argv einfügen (ich habe für das folgende Beispiel None gewählt, aber das spielt wirklich keine Rolle).
Der folgende Code erstellt einen Beispielparser und eine Reihe von Optionen, extrahiert ein Array zulässiger Schalter aus dem Parser (mit ein wenig Instanzvariable magic), iteriert dann durch sys.argv und findet jedes Mal ein erlaubte Schalter, es überprüft, um zu sehen, ob es gegeben wurde, ohne irgendwelche Argumente ihm zu folgen. Wenn nach einem Wechsel kein Argument vorhanden ist, wird die leere Zeichenfolge in den Befehl Zeile eingefügt. Nach dem Ändern von sys.argv wird der Parser aufgerufen, und Sie können nach Optionen suchen, deren Werte "" sind, und entsprechend handeln.
#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)
#Build a list of allowed switches, in this case ['-d', '--delete', '-a', '--add'] so that you can check if something
#found on sys.argv is indeed a valid switch. This is trivial to make by hand in a short example, but if a program has
#a lot of options, or if you want an idiot-proof way of getting all added options without modifying a list yourself,
#this way is durable. If you are using OptionGroups, simply run the loop below with each group's option_list field.
allowed_switches = []
for opt in parser.option_list:
#Add the short (-a) and long (--add) form of each switch to the list.
allowed_switches.extend(opt._short_opts + opt._long_opts)
#Insert empty-string values into sys.argv whenever a switch without arguments is found.
for a in range(len(sys.argv)):
arg = sys.argv[a]
#Check if the sys.argv value is a switch
if arg in allowed_switches:
#Check if it doesn't have an accompanying argument (i.e. if it is followed by another switch, or if it is last
#on the command line)
if a == len(sys.argv) - 1 or argv[a + 1] in allowed_switches:
sys.argv.insert(a + 1, "")
options, args = parser.parse_args()
#If the option is present (i.e. wasn't set to the default value)
if not (options.to_delete == PARSER_DEFAULTVAL):
if options.droptables_ids_csv == "":
#The switch was not used with any arguments.
...
else:
#The switch had arguments.
...
Das Problem mit dieser Variante ist, dass '--for = bar' nicht funktioniert _parser.py: error: --foo Option nimmt keinen Wert' – Tobias