I used to write my (simple) Python programs in Python 2, but it seems that Python 3 is quite mature. I now have a CLI program called ratjuice.py and when I execute it the program asks for a command input (which I have made some tab completion thing for).
So I might have commands like html which could output the subcommands like parse or destroy. I might want to use the command html parse rat.html. So I am looking for a Python module which allows me to parse this input based on a white list. So I would basically tell what is allowed and the rest is ignored or rejected (I might forget some things if I sanitize the input...)
Is there any good way to do this other than mere string manipulation?
2 Answers 2
A string parsing version I just slapped together that requires no additional libraries, that works with your "whitelist" idea:
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')