更多的處理:在Jython中解析命令行
作者:佚名
經(jīng)常會(huì)需要對命令行參數(shù)進(jìn)行比 sys.argv 所提供的更多的處理,因此在Jython中解析命令行成了一個(gè)有效的手段。本文介紹了如何在Jython中解析命令行。
在Jython中解析命令行
經(jīng)常會(huì)需要對命令行參數(shù)進(jìn)行比 sys.argv 所提供的更多的處理。parseArgs 函數(shù)可以用于作為一組位置參數(shù)和一個(gè)開關(guān)字典得到任意的命令行參數(shù)。
因此,繼續(xù) 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
可以如下使用這個(gè)函數(shù)(在文件 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}
這樣就實(shí)現(xiàn)了在Jython中解析命令行。
【編輯推薦】
責(zé)任編輯:yangsai
來源:
網(wǎng)絡(luò)