2012-08-25 5 views
19

In tutti i miei script utilizzo le flag standard --help e --version, tuttavia non riesco a capire come creare un.Python argparse required = Vero ma --versione di funzionalità?

import sys, os, argparse 

parser = argparse.ArgumentParser(description='How to get --version to work?') 

parser.add_argument('--version', action='store_true', 
        help='print version information') 
parser.add_argument('-H', '--hostname', dest='hostname', required=True, 
        help='Host name, IP Address') 
parser.add_argument('-d', '--database', dest='database', required=True, 
        help='Check database with indicated name') 
parser.add_argument('-u', '--username', dest='username', required=True, 
        help='connect using the indicated username') 
parser.add_argument('-p', '--password', dest='password', required=True, 
        help='use the password to authenticate the connection') 

args = parser.parse_args() 

if args.version == True: 
    print 'Version information here' 

$ ./arg.py --version 
usage: arg.py [-h] [--version] -H HOSTNAME -d DATABASE -u USERNAME -p PASSWORD 
arg.py: error: argument -H/--hostname is required 

Sì, voglio --hostnamee altri richieste, ma ho sempre vogliono --version di lavorare in modo appropriato come --help (e -h).

$ ./arg.py --help 
usage: arg.py [-h] [--version] -H HOSTNAME -d DATABASE -u USERNAME -p PASSWORD 

How to get --version to work? 

optional arguments: 
    -h, --help   show this help message and exit 
    --version    print version information 
    -H HOSTNAME, --hostname HOSTNAME 
         Host name, IP Address 
    -d DATABASE, --database DATABASE 
         Check database with indicated name 
    -u USERNAME, --username USERNAME 
         connect using the indicated username 
    -p PASSWORD, --password PASSWORD 
         use the password to authenticate the connection 

Qualsiasi aiuto su come ottenere --version a lavorare?

+0

dovrebbe essere (per evitare errori chiave :) se 'versione' in args: print 'Le informazioni sulla versione qui' – radtek

risposta

34

V'è una speciale versione action parola chiave argomento add_argument (come documentato qui: argparse#action).
Prova questa (copiato dal codice di lavoro):

parser.add_argument('-V', '--version', 
        action='version',      
        version='%(prog)s (version 0.1)') 
+4

come documentato in http: // docs .python.org/library/argparse.html # action, +1. Si noti che questo è esattamente ciò che l'OP chiede; un metodo per far funzionare un argomento '--version', quando ci sono argomenti' required = True'. –