TL; DR
Utilizzare l' nargsopzione o l' 'append'impostazione actiondell'opzione (a seconda di come si desidera che l'interfaccia utente si comporti).
nargs
parser.add_argument('-l','--list', nargs='+', help='<Required> Set flag', required=True)
# Use like:
# python arg.py -l 1234 2345 3456 4567
nargs='+'accetta 1 o più argomenti, nargs='*'accetta zero o più.
aggiungere
parser.add_argument('-l','--list', action='append', help='<Required> Set flag', required=True)
# Use like:
# python arg.py -l 1234 -l 2345 -l 3456 -l 4567
Con appendte fornisci l'opzione più volte per costruire l'elenco.
Non usare type=list!!! - Probabilmente non esiste situazione in cui si desidera utilizzare type=listcon argparse. Mai.
Diamo un'occhiata più in dettaglio ad alcuni dei diversi modi in cui si potrebbe provare a fare questo, e il risultato finale.
import argparse
parser = argparse.ArgumentParser()
# By default it will fail with multiple arguments.
parser.add_argument('--default')
# Telling the type to be a list will also fail for multiple arguments,
# but give incorrect results for a single argument.
parser.add_argument('--list-type', type=list)
# This will allow you to provide multiple arguments, but you will get
# a list of lists which is not desired.
parser.add_argument('--list-type-nargs', type=list, nargs='+')
# This is the correct way to handle accepting multiple arguments.
# '+' == 1 or more.
# '*' == 0 or more.
# '?' == 0 or 1.
# An int is an explicit number of arguments to accept.
parser.add_argument('--nargs', nargs='+')
# To make the input integers
parser.add_argument('--nargs-int-type', nargs='+', type=int)
# An alternate way to accept multiple inputs, but you must
# provide the flag once per input. Of course, you can use
# type=int here if you want.
parser.add_argument('--append-action', action='append')
# To show the results of the given option to screen.
for _, value in parser.parse_args()._get_kwargs():
if value is not None:
print(value)
Ecco l'output che puoi aspettarti:
$ python arg.py --default 1234 2345 3456 4567
...
arg.py: error: unrecognized arguments: 2345 3456 4567
$ python arg.py --list-type 1234 2345 3456 4567
...
arg.py: error: unrecognized arguments: 2345 3456 4567
$ # Quotes won't help here...
$ python arg.py --list-type "1234 2345 3456 4567"
['1', '2', '3', '4', ' ', '2', '3', '4', '5', ' ', '3', '4', '5', '6', ' ', '4', '5', '6', '7']
$ python arg.py --list-type-nargs 1234 2345 3456 4567
[['1', '2', '3', '4'], ['2', '3', '4', '5'], ['3', '4', '5', '6'], ['4', '5', '6', '7']]
$ python arg.py --nargs 1234 2345 3456 4567
['1234', '2345', '3456', '4567']
$ python arg.py --nargs-int-type 1234 2345 3456 4567
[1234, 2345, 3456, 4567]
$ # Negative numbers are handled perfectly fine out of the box.
$ python arg.py --nargs-int-type -1234 2345 -3456 4567
[-1234, 2345, -3456, 4567]
$ python arg.py --append-action 1234 --append-action 2345 --append-action 3456 --append-action 4567
['1234', '2345', '3456', '4567']
Asporto :
- Usa
nargsoaction='append'
nargspuò essere più semplice dal punto di vista dell'utente, ma può non essere intuitivo se ci sono argomenti posizionali perché argparsenon può dire quale dovrebbe essere un argomento posizionale e ciò che appartiene a nargs; se hai argomenti posizionali, action='append'potresti finire per essere una scelta migliore.
- Quanto sopra è solo vero se
nargsè dato '*', '+'o '?'. Se si fornisce un numero intero (come 4), non ci saranno problemi a mescolare opzioni nargse argomenti posizionali perché argparsesaprà esattamente quanti valori aspettarsi per l'opzione.
- Non usare le virgolette sulla riga di comando 1
- Non utilizzare
type=list, poiché restituirà un elenco di elenchi
- Questo accade perché sotto il cofano si
argparseusa il valore di typeforzare ogni singolo argomento dato che hai scelto type, non l'aggregato di tutti gli argomenti.
- Puoi usare
type=int(o qualsiasi altra cosa) per ottenere un elenco di ints (o qualunque altra cosa)
1 : Non intendo in generale .. Voglio dire che usare le virgolette per passare un elencoargparse non è quello che vuoi.