2012-03-15 3 views
19

Esiste un modulo Python per che fa gli argomenti della riga di comando gem/git-style da? Quello che intendo per gem/git style è:argomenti della riga di comando gem/git-style in Python

$ ./MyApp.py 
The most commonly used MyApp commands are: 
    add  Add file contents to the index 
    bisect  Find by binary search the change that introduced a bug 
    branch  List, create, or delete branches 
    checkout Checkout a branch or paths to the working tree 
    ... 

$ ./MyApp.py branch 
    * current-branch 
    master 

Senza argomenti, l'output indica come procedere. E c'è un comando speciale "help":

$ ./MyApp.py help branch 

Che ti dà suggerimenti più approfonditi sul comando "ramo".

Edit: E per facendo voglio dire che fa la stampa utilizzo per voi, esce con input non valido, corre le funzioni secondo la vostra specifica CLI. Ordinamento di "URL mapper" per la riga di comando.

risposta

30

Sì, argparse con add_subparser().

È tutto ben spiegato nella sezione Sub-commands.

Copia uno degli esempi da lì:

>>> parser = argparse.ArgumentParser() 
>>> subparsers = parser.add_subparsers() 
>>> checkout = subparsers.add_parser('checkout', aliases=['co']) 
>>> checkout.add_argument('foo') 
>>> parser.parse_args(['checkout', 'bar']) 
Namespace(foo='bar') 

Edit: Purtroppo non c'è nessuna auto generato speciale comando help, ma è possibile ottenere il messaggio di aiuto verbose (che ti sembra di volere) con -h o --help come uno normalmente dopo il comando:

$ ./MyApp.py branch --help 

Con verbose non voglio dire che è come una pagina di manuale, è come ogni altro --help tipo di aiuto: sfogliare tutti gli argomenti, ecc ...

Esempio:

>>> parser = argparse.ArgumentParser() 
>>> subparsers = parser.add_subparsers(description='Sub description') 
>>> checkout = subparsers.add_parser('checkout', description='Checkout description') 
>>> checkout.add_argument('foo', help='This is the foo help') 
>>> parser.parse_args(['checkout', '--help']) 
usage: checkout [-h] foo 

Checkout description 

positional arguments: 
    foo   This is the foo help 

optional arguments: 
    -h, --help show this help message and exit 

Se è necessario, dovrebbe essere facile da implementare un comando help che reindirizza a --help.

+0

Potrebbe essere utile sottolineare che la parola chiave 'aliases' a' subparsers.add_parser() 'è nuova su Python 3 e non è disponibile in Python 2.7. – Juan

+0

Attenzione con argparse: una volta che si iniziano ad aggiungere subparser annidati, le cose diventano molto complicate. Vedi ad esempio: http://bugs.python.org/issue9253 – Federico

+0

Il grande pacchetto [click] (http://click.pocoo.org/) offre questa funzionalità fuori dalla scatola! Controlla il tutorial * complex * [qui] (http://click.pocoo.org/5/complex/) –

4

Un hack ragionevole per ottenere il comportamento gemma/stile git "help" (ho appena scritto questo per quello che sto lavorando in ogni caso):

parser = argparse.ArgumentParser() 
subparsers = parser.add_subparsers(dest='sub_commands') 
parser_branch = subparsers.add_parser('branch', description='list of branches') 
parser_help = subparsers.add_parser('help') 
parser_help.add_argument('command', nargs="?", default=None) 

# I can't find a legitimate way to set a default subparser in the docs 
# If you know of one, please let me know! 
if len(sys.argv) < 2: 
    sys.argv.append('--help') 

parsed = parser.parse_args() 

if parsed.sub_commands == "help": 
    if not parsed.command: 
     parser.parse_args(['--help']) 
    else: 
     parser.parse_args([parsed.command, '--help']) 

argparse è sicuramente un passo avanti rispetto optparse e altri soluzioni python che ho incontrato. Ma IMO lo stile gemma/git di gestione degli argomenti è solo un modo più logico e più sicuro di fare le cose, quindi è fastidioso che non sia supportato.