1

以前は (単純な) Python プログラムを Python 2 で書いていましたが、Python 3 はかなり成熟しているようです。現在、CLI プログラムが呼び出されてratjuice.pyおり、実行すると、プログラムはコマンド入力を要求します (これにはタブ補完をいくつか作成しました)。

したがって、またはhtmlのようなサブコマンドを出力できるようなコマンドがあるかもしれません。コマンドを使用したい場合があります。そのため、ホワイト リストに基づいてこの入力を解析できる Python モジュールを探しています。したがって、基本的に何が許可されているかを伝え、残りは無視または拒否されます (入力をサニタイズすると、いくつかのことを忘れる可能性があります...)parsedestroyhtml parse rat.html

単なる文字列操作以外にこれを行う良い方法はありますか?

4

2 に答える 2

1

cmdモジュールを見てください。行編集を行い、履歴を記憶します (おそらく)。

于 2012-08-15T18:43:34.517 に答える
1

あなたの「ホワイトリスト」のアイデアで動作する、追加のライブラリを必要としない、私が一緒に平手打ちした文字列解析バージョン:

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')
于 2012-08-15T18:45:30.770 に答える