在Jython中解析命令行
经常会需要对命令行参数进行比 sys.argv 所提供的更多的处理。parseArgs 函数可以用于作为一组位置参数和一个开关字典得到任意的命令行参数。
因此,继续 JavaUtils.py模块片段,我们看到:
- def parseArgs (args, validNames, nameMap=None):
- """ Do some simple command line parsing. """
- # validNames is a dictionary of valid switch names -
- # the value (if any) is a conversion function
- switches = {}
- positionals = []
- for arg in args:
- if arg[0] == '-': # a switch
- text = arg[1:]
- name = text; value = None
- posn = text.find(':') # any value comes after a :
- if posn >= 0:
- name = text[:posn]
- value = text[posn + 1:]
- if nameMap is not None: # a map of valid switch names
- name = nameMap.get(name, name)
- if validNames.has_key(name): # or - if name in validNames:
- mapper = validNames[name]
- if mapper is None: switches[name] = value
- else: switches[name] = mapper(value)
- else:
- print "Unknown switch ignored -", name
- else: # a positional argument
- positionals.append(arg)
- return positionals, switches
可以如下使用这个函数(在文件 parsearg.py 中):
- from sys import argv
- from JavaUtils import parseArgs
- switchDefs = {'s1':None, 's2':int, 's3':float, 's4':int}
- args, switches = parseArgs(argv[1:], switchDefs)
- print "args:", args
- print "switches:", switches
对于命令c:\>jython parsearg.py 1 2 3 -s1 -s2:1 ss -s4:2,它打印:
- args: ['1', '2', '3', 'ss']
- switches: {'s4': 2, 's2': 1, 's1': None}
这样就实现了在Jython中解析命令行。
【编辑推荐】