Wednesday, December 14, 2005

命令列參數

想要讓command line paramaters比較容易處理,shell可以用:getopts,至於c,也可以呼叫getopt(要include unistd.h)。Python裡就是import optparse(python2.3(含)之後已經是標準的模組)。

#!/usr/bin/env python
import optparse
if __name__ == "__main__":
usage = "Usage %prog [options]"
p = optparse.OptionParser(usage=usage)
p.add_option("-t","--test",action="store_true",dest="dotest",default=False,help="test case")
(options,args) = p.parse_args()
if options.dotest:
print 'do test'
else:
print 'No action'

在命令列執行:

>./test.py -t
do test
>./test.py -h
usage: Usage test.py [options]

options:
-h, --help show this help message and exit
-t, --test test case
>

No comments: