更多的处理:在Jython中解析命令行
在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,它打印:
相关推荐
吹云 2020-11-05
84407805 2020-11-01
曾是土木人 2020-10-31
87201442 2020-10-15
java0 2020-09-29
81437716 2020-09-18
81437716 2020-09-13
bluecarrot 2020-09-11
myCat 2020-09-09
83427718 2020-09-07
85560694 2020-09-03
89520991 2020-08-21
89550191 2020-08-09
katie000 2020-08-04
hunningtu 2020-07-30
89961330 2020-07-28
yuzhongdelei0 2020-07-28
yuzhongdelei0 2020-07-27