这正是 OptionParser 旨在处理的内容!
考虑以下代码:
import sys
import os
from optparse import OptionParser
__all__ = []
__version__ = 0.1
__date__ = '2014-01-21'
__updated__ = '2014-01-21'
def main(argv=None):
'''Command line options.'''
program_name = os.path.basename(sys.argv[0])
program_version = "v0.1"
program_build_date = "%s" % __updated__
program_version_string = '%%prog %s (%s)' % (program_version, program_build_date)
program_longdesc = '''This will be displayed beneath your help information''' # optional - give further explanation about what the program does
program_license = "Copyright 2014 Code Tester (Jython Dev Inc.) \
Licensed under the Apache License 2.0\nhttp://www.apache.org/licenses/LICENSE-2.0"
if argv is None:
argv = sys.argv[1:]
try:
# setup option parser
parser = OptionParser(version=program_version_string, epilog=program_longdesc, description=program_license)
parser.add_option("-i", "--in", dest="infile", help="set input path [default: %default]", metavar="FILE")
parser.add_option("-o", "--out", dest="outfile", help="set output path [default: %default]", metavar="FILE")
parser.add_option("-d", "--debug", dest="modeDebug", action="store_true", help="Prints additional debug information")
parser.add_option("-m", "--map", dest="listKVPs", action="append", help="Key value pair mappings (i.e. left=right)", metavar="KVP")
parser.add_option("-r", "--role", dest="listProtectedRoles", action="append", help="Protected system roles to use (multiple allowed)", metavar="Role")
parser.add_option("-u", "--user", dest="listProtectedUsers", action="append", help="Protected system users to be used (multiple allowed)", metavar="User")
# set defaults
parser.set_defaults(outfile="./out.txt", infile="./in.txt")
# process options
(opts, args) = parser.parse_args(argv)
if opts.modeDebug:
print("Running in DEBUG mode")
if opts.infile:
print("infile = %s" % opts.infile)
if opts.outfile:
print("outfile = %s" % opts.outfile)
if opts.listKVPs:
print("KVP's = %s" % opts.listKVPs)
if opts.listProtectedRoles:
print("Protected Roles = %s" % opts.listProtectedRoles)
if opts.listProtectedUsers:
print("Protected Users = %s" % opts.listProtectedUsers)
'''
Do something interesting with the parameters here!
'''
except Exception, e:
indent = len(program_name) * " "
sys.stderr.write(program_name + ": " + repr(e) + "\n")
sys.stderr.write(indent + " for help use --help")
return 2
if __name__ == "__main__":
sys.exit(main())
如果您使用 -h(或 --help)运行它,您将获得以下信息:
Usage: OptParseExample.py [options]
Copyright 2014 Code Tester (Jython Dev Inc.)
Licensed under the Apache License 2.0
http://www.apache.org/licenses/LICENSE-2.0
Options:
--version show program's version number and exit
-h, --help show this help message and exit
-i FILE, --in=FILE set input path [default: ./in.txt]
-o FILE, --out=FILE set output path [default: ./out.txt]
-d, --debug Prints additional debug information
-m KVP, --map=KVP Key value pair mappings (i.e. left=right)
-r Role, --role=Role Protected system roles to use (multiple allowed)
-u User, --user=User Protected system users to be used (multiple allowed)
This will be displayed beneath your help information
现在,如果我们使用更多参数运行它,即:
testScript.py -d -i input.txt -o output.txt -m jython=cool -r Admins -r DomainAdmins
我们得到显示的输出:
Running in DEBUG mode
infile = input.txt
outfile = output.txt
KVP's = ['jython=cool']
Protected Roles = ['Admins', 'DomainAdmins']
注意几点:
- 命令行上参数的顺序并不重要(只要参数提供了相关的标志)
- 在这种情况下,-d 选项用作“store_true”参数,表示它是一个布尔标志
- 其他参数都取附加值
- 如果带值的参数可以接受多个值,则可以将其声明为列表(使用附加操作)
- 处理完所有参数后,您仍然可以通过“args”变量获得任何其他命令行参数。
有关更多信息,请查看http://jython.org/docs/library/optparse.html