1

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

1

Have a look at the cmd module. It does line-editing and remembers history (supposedly).

Sign up to request clarification or add additional context in comments.

Comments

1

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')

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.