Argparse in Python 2.7 si può dire di richiedere un minimo di due argomenti?
Domanda
La mia applicazione è un'utilità di confronto dei file specializzata e ovviamente non ha senso confrontare un solo file, quindi nargs='+'
non è del tutto appropriato.
nargs=N
solo tranne un massimo di N
Argomenti, ma devo accettare un numero infinito di argomenti purché ce ne siano almeno due.
Soluzione
La risposta breve è che non puoi farlo perché NARGS non supporta qualcosa come "2+".
La risposta lunga è che puoi alternativa che usando qualcosa del genere:
parser = argparse.ArgumentParser(usage='%(prog)s [-h] file file [file ...]')
parser.add_argument('file1', nargs=1, metavar='file')
parser.add_argument('file2', nargs='+', metavar='file', help=argparse.SUPPRESS)
namespace = parser.parse_args()
namespace.file = namespace.file1 + namespace.file2
I trucchi di cui hai bisogno sono:
- Uso
usage
Per fornirti la tua stringa di utilizzo al parser - Uso
metavar
Per visualizzare un argomento con un nome diverso nella stringa di aiuto - Uso
SUPPRESS
Per evitare di mostrare aiuto per una delle variabili - Unisci due variabili diverse solo aggiungendo un nuovo attributo al
Namespace
oggetto che il parser restituisce
L'esempio sopra produce la seguente stringa di aiuto:
usage: test.py [-h] file file [file ...]
positional arguments:
file
optional arguments:
-h, --help show this help message and exit
e fallirà ancora quando vengono superati meno di due argomenti:
$ python test.py arg
usage: test.py [-h] file file [file ...]
test.py: error: too few arguments
Altri suggerimenti
Non potresti fare qualcosa del genere:
import argparse
parser = argparse.ArgumentParser(description = "Compare files")
parser.add_argument('first', help="the first file")
parser.add_argument('other', nargs='+', help="the other files")
args = parser.parse_args()
print args
Quando lo eseguo con -h
Ottengo:
usage: script.py [-h] first other [other ...]
Compare files
positional arguments:
first the first file
other the other files
optional arguments:
-h, --help show this help message and exit
Quando lo eseguo con un solo argomento, non funzionerà:
usage: script.py [-h] first other [other ...]
script.py: error: too few arguments
Ma due o più argomenti vanno bene. Con tre argomenti stampa:
Namespace(first='one', other=['two', 'three'])