2011-07-31 59 views
1
""" 
Saves a dir listing in a file 
Usage: python listfiles.py -d dir -f filename [flags] 
Arguments: 
    -d, --dir    dir; ls of which will be saved in a file 
    -f, --file    filename (if existing will be overwritten) 
Flags: 
    -h, --help    show this help 
    -v, --verbose   be verbose 
"""   

... 

def usage(): 
    print __doc__ 

def main(args): 
    verbose = False 
    srcdir = filename = None 
    try: 
    opts, args = getopt.getopt(args, 
           'hvd:f:', ['help', 'verbose', 'dir=', 'file=']) 
    except getopt.GetoptError: 
    usage() 
    sys.exit(2) 
    for opt, arg in opts: 
    if opt in ('-h', '--help'): 
     usage() 
     sys.exit(0) 
    if opt in ('-v', '--verbose'): 
     verbose = True 
    elif opt in ('-d', '--dir'): 
     srcdir = arg 
    elif opt in ('-f', '--file'): 
     filename = arg 
    if srcdir and filename: 
    fsock = open(filename, 'w') 
    write_dirlist_tosock(srcdir, fsock, verbose) 
    fsock.close() 
    else: 
    usage() 
    sys.exit(1) 

if __name__ == '__main__': 
    main(sys.argv[1:]) 

我不確定是否pythonic使用getopt()也可以處理強制參數。希望得到一些建議我是否還需要用getopt解析強制性參數(...)

+9

我可以推薦[argparse](http://docs.python.org/library/argparse.html)。 –

+0

另外檢查plac(更簡單):http://pypi.python.org/pypi/plac –

回答

3

getopt模塊只對那些誰已經熟悉C,同一模塊Python標準參數處理是argparse用戶。

1

「強制選項」是一個矛盾,並且通常不被各種選項解析庫支持;您應該考慮將強制性參數作爲位置參數,而不是由選項解析器進行分析,這與常用實踐相符得多。

+0

是的!這正是我的問題,我想我會編輯標題。您能否詳細說明「在執行解析器時考慮將強制參數作爲位置參數」 –

+0

,通常返回一個2-tuple,第一項是解析的選項,第二項是解析器參數的* rest *沒有認出。這些被稱爲位置參數,並且按照特定順序期望它們的某種組合是典型的。 – SingleNegationElimination

相關問題