使用命令行时,如果要添加选项的话,python 2.3里新增加了一个模块叫optparse,也是专门来处理命令行选项的。
from optparse import OptionParser parser = OptionParser() parser.add_option("-p", "--pdbk", action="store_true", dest="pdcl", default=False, help="write pdbk data to oracle db") parser.add_option("-z", "--zdbk", action="store_true", dest="zdcl", default=False, help="write zdbk data to oracle db") (options, args) = parser.parse_args() if options.pdcl==True: print 'pdcl is true' if options.zdcl==True: print 'zdcl is true' |
基本使用流程:
》1.產生一個 optparse.OptionParser 的物件。可以在產生時將"程式的命令列說明" (usage) 做為參數,交給 OptionParser 的建構子:
1 |
from optparse import OptionParser MSG_USAGE = "myprog[ -f <filename>][ -s <xyz>] arg1[, arg2...]" optParser = OptionParser(MSG_USAGE) |
1 |
optParser.add_option("-f", "--file", action = "store", type = "string", dest = "fileName") |
1 |
optParser.add_option("-s", "--someopt", type = "string", dest = "someopt") |
1 |
fakeArgs = ['-f', 'thefile.txt', '-s', 'xyz', 'arg1', 'arg2', 'arge'] options, args = optParser.parse_args(fakeArgs) print options.fileName print options.someopt print args |
1 |
thefile.txt xyz ['arg1', 'arg2', 'arge'] |
1 |
parser.add_option("-v", action="store_true", dest="verbose") parser.add_option("-q", action="store_false", dest="verbose") opts, args = parser.parse_args() |
1 |
parser.add_option("-v", action="store_true", dest="verbose", default = True) parser.add_option("-q", action="store_false", dest="verbose") opts, args = parser.parse_args() |
1 |
parser.add_option("-v", action="store_true", dest="verbose", default=False) parser.add_option("-q", action="store_false", dest="verbose", default=True) |
1 |
parser.add_option("-f", action="store", dest="fileName", default = "defaultConfig.txt") |
1 |
parser.add_option("-v", action="store_true", dest="verbose", default=False, help="make lots of noise [default]") |
1 |
usage: <yourscript> [options] arg1 arg2 options: -h, --help show this help message and exit -v, --verbose make lots of noise [default] -q, --quiet be vewwy quiet (I'm hunting wabbits) -fFILE, --file=FILE write output to FILE -mMODE, --mode=MODE interaction mode: one of 'novice', 'intermediate' [default], 'expert' |
1 |
usage = "usage: %prog [options] arg1 arg2" |
1 |
usage = "usage: myprog [options] arg1 arg2" |
1 |
"usage: %prog [options]" |