我刚刚拼凑的一个字符串解析版本,不需要额外的库,它适用于您的“白名单”想法:
def foo1(bar):
print '1. ' + bar
def foo2(bar):
print '2. ' + bar
def foo3(bar):
print '3. ' + bar
cmds = {
'html': {
'parse': foo1,
'dump': foo2,
'read': {
'file': foo3,
}
}
}
def argparse(cmd):
cmd = cmd.strip()
cmdsLevel = cmds
while True:
candidate = [key for key in cmdsLevel.keys() if cmd.startswith(key)]
if not candidate:
print "Failure"
break
cmdsLevel = cmdsLevel[candidate[0]]
cmd = cmd[len(candidate[0]):].strip()
if not isinstance(cmdsLevel, dict):
cmdsLevel(cmd)
break
argparse('html parse rat.html')
argparse('foo')
argparse('html read file rat.html')
argparse('html dump rat.html')