2012-08-25 32 views
19

在我所有的腳本中,我使用標準標記--help--version,但我似乎無法弄清楚如何製作--versionparser.add_argument(..., required=True)Python argparse required = True但是--version功能?

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 

是的,我想--hostname和其他必需的,但我始終--version--help(和-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 

在得到--version工作的任何幫助嗎?

+0

應該是(爲避免鍵錯誤:) 如果「版本」在args: 打印「這裏的版本信息」 – radtek

回答

34

有一個特殊的版本action關鍵字參數add_argument(如這裏記載:argparse#action)。
試試這個(從工作代碼複製):

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

如HTTP記載://文檔.python.org/library/argparse.html#action,+1。請注意,這正是OP要求的;當有'required = True'參數時,一個使'--version'參數有效的方法。 –