2012-08-15 46 views
1

我曾經在Python 2中編寫我的(簡單)Python程序,但似乎Python 3已經相當成熟。我現在有一個名爲ratjuice.py的CLI程序,當我執行它時,程序要求輸入一個命令(我已經做了一些標籤補全的工作)。解析命令CLI程序Python

所以我可能會有像html這樣的命令,它可以輸出像parsedestroy這樣的子命令。我可能想要使用命令html parse rat.html。所以我正在尋找一個Python模塊,它允許我根據白名單解析此輸入。所以,我基本上分不清什麼是允許的,其餘部分被忽略或拒絕(如果我淨化輸入我會忘記一些事情...)

有任何辦法做到這一點比單純的字符串操作等?

回答

1

看看cmd模塊。它行編輯和記憶歷史(據說)。

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