更多的处理:在Jython中解析命令行

在Jython中解析命令行

经常会需要对命令行参数进行比 sys.argv 所提供的更多的处理。parseArgs 函数可以用于作为一组位置参数和一个开关字典得到任意的命令行参数。

因此,继续 JavaUtils.py模块片段,我们看到:

 
 
 
  1. def parseArgs (args, validNames, nameMap=None):  
  2.     """ Do some simple command line parsing. """ 
  3.     # validNames is a dictionary of valid switch names -  
  4.     #   the value (if any) is a conversion function  
  5.     switches = {}  
  6.     positionals = []  
  7.     for arg in args:  
  8.         if arg[0] == '-':               # a switch  
  9.             text = arg[1:]  
  10.             name = text; value = None 
  11.             posn = text.find(':')       # any value comes after a :  
  12.             if posn >= 0:  
  13.                 name = text[:posn]  
  14.                 value = text[posn + 1:]  
  15.             if nameMap is not None:     # a map of valid switch names  
  16.                 name = nameMap.get(name, name)  
  17.             if validNames.has_key(name):   # or - if name in validNames:  
  18.                 mapper = validNames[name]  
  19.                 if mapper is None: switches[name] = value  
  20.                 else:              switches[name] = mapper(value)  
  21.             else:  
  22.                 print "Unknown switch ignored -", name  
  23.  
  24.         else:                           # a positional argument  
  25.             positionals.append(arg)  
  26.     return positionals, switches  

可以如下使用这个函数(在文件 parsearg.py 中):

 
 
 
  1. from sys import argv  
  2. from JavaUtils import parseArgs  
  3.  
  4. switchDefs = {'s1':None's2':int, 's3':float, 's4':int}  
  5. args, switches = parseArgs(argv[1:], switchDefs)  
  6. print "args:", args  
  7. print "switches:", switches  

对于命令c:\>jython parsearg.py 1 2 3 -s1 -s2:1 ss -s4:2,它打印:

 
 
 
  1. args: ['1''2''3''ss']  
  2. switches: {'s4'2's2'1's1'None

这样就实现了在Jython中解析命令行。

【编辑推荐】

  1. 如何将Jython类型转换为Java类型
  2. Jython访问Java属性文件的方法一览
  3. 用于Jython连接Java的JavaUtils模块
  4. Jython线程示例:定义共享缓冲区
  5. 与Java语言相比Jython开发的独特性能
THE END