這裏有一個演示腳本,我幾個月前寫的時候,我的同事和我學習argparse模塊。它說明了幾個模塊的行爲和功能:
import sys
import argparse
def parse_command_line():
# Define our argument parser.
ap = argparse.ArgumentParser(
description = 'This is a demo app for the argparse module.',
epilog = 'This text will appear after options.',
usage = '%(prog)s [options]', # Auto-generated by default.
add_help = False, # Default is True.
)
# A grouping of options in the help text.
gr = ap.add_argument_group('Required arguments')
# A positional argument. This is indicated by the absense
# of leading minus signs.
gr.add_argument(
'task',
choices = ['get', 'put'],
help = 'Task to be performed.', # Help text about an option.
metavar = 'TASK', # Placeholder to be used in an option's help text.
# The default in this case would be "{get,put}".
)
# Another group.
gr = ap.add_argument_group('Common options')
# A basic option.
gr.add_argument(
'-s', '--subtask',
action = 'store', # This is the default.
# One value will be stored, as a string,
# in opt.subtask
)
# A required option, with type conversion.
gr.add_argument(
'-u', '--user',
required = True, # Options can be made mandatory.
# However, positional arguments can't be made optional.
type = int, # Convert opt.user to an integer.
# By default, it would be a string.
)
# A flag option.
gr.add_argument(
'--overwrite',
dest = 'clobber', # Store in opt.clobber rather than opt.overwrite.
action = 'store_true', # If option is supplied, opt.clobber == True.
)
# Another group.
gr = ap.add_argument_group('Some other options')
# An option with multiple values.
gr.add_argument(
'--datasets',
metavar = 'DATASET', # Default would be DATASETS.
nargs = '+', # If option is used, it takes 1 or more arguments.
# Will be stored as a list in opt.datasets.
help = "The datasets to use for frobnication.",
)
# An option with a specific N of values.
gr.add_argument(
'--bar',
nargs = 1, # Takes exactly one argument. Differs from a basic
# option because opt.bar will be a list rather
# than a string.
default = [], # Default would be None.
)
# A file option.
gr.add_argument(
'--log',
type = argparse.FileType('w'), # Will open a file for writing.
default = sys.stdout,
help = 'Log file (default: STDOUT)',
)
# Another group.
gr = ap.add_argument_group('Program information')
# A version option.
gr.add_argument(
'-v', '--version',
action = 'version', # Will display version text and exit.
version = 'argparse_demo v1.2.0', # The version text.
)
# A help option.
gr.add_argument(
'-h', '--help',
action = 'help', # Will display help text and exit.
)
# Parse the options.
# If given no arguments, parse_args() works with sys.argv[1:].
# And the object it returns will be of type Namespace.
opt = ap.parse_args()
return opt
command_lines = [
'argparse_demo.py put -u 1',
'argparse_demo.py get -u 234 --over --data a b c --bar XYZ -s munch --log _log.txt',
'argparse_demo.py -h', # Will exit() here.
]
for c in command_lines:
sys.argv = c.split()
opt = parse_command_line()
print opt
嗨,gclj5,謝謝你的回答。我正在使用2.4.3。我聽說過這個optparse,但我不知道如何在代碼中使用它。例如我怎麼能把它集成到addcd函數中?在哪裏以及如何添加它? – pepero 2010-10-24 12:02:30
我不知道你的程序的確切結構,所以我不能告訴你究竟在哪裏添加它。但我添加了一些示例代碼來說明optparse包的用法。一般的想法是讓CLI解析代碼使用解析的選項調用相應的函數。 – gclj5 2010-10-24 12:38:57
嗨,gclj5,非常感謝你的代碼。它是args [0:],而不是args [1:],因爲參數是作爲方法的輸入。我修改了原始帖子中的代碼。但仍然存在一些問題。當存在一些異常(錯誤類型或缺失選項)時,此選項分析將退出整個程序,而不是退出相關方法。我們怎麼能解決這個問題? – pepero 2010-10-25 10:14:35