在python中使用不同路由构建命令行的最佳实践

时间:2016-10-21 05:18:10

标签: python command-line command-line-interface

我正在构建一个Twitter机器人,我与之通信的方式是使用Twitter DM。我希望有简单的命令,它们有自己的分层路由。例如:

Follow
|
|--> Followers
|       |
|       |--> {screen_name}
|          
|
|--> {screen_name} 

User
|
|--> add
|
|--> delete

Hashtags
|
|--> add
|
|--> delete

例如,在跟随所有@barackobama粉丝的用法之后,可以输入“Follow Followers barackobama”。什么是解析它的最佳方法?

提前致谢,

1 个答案:

答案 0 :(得分:0)

对于像这样的简单情况,我倾向于使用带有命名捕获组的正则表达式。

示例:

import re

def follow(name):
    print 'following ' + name 

cmds = {
        'Follow (?P<name>[a-z]+)': follow,
}

a_cmd = 'Follow foobar'
for expr, action in cmds.iteritems():
    # try to match the pattern onto the given command
    m = re.match(expr, a_cmd, re.I)
    if m:
        # if matched, call the corresponding action, using
        # the named groups as keyword arguments.
        action(**m.groupdict())

为了更加花哨,可以用包含更多铃声和口哨声的类替换简单的回调动作。如有疑问,KISS。 : - )

编辑:正如一些程序员老兄指出的那样,这在某种程度上是对字典的滥用。 (但它在屏幕上显示出漂亮的简洁外观)。更清晰的解决方案是命名元组列表:

from collections import namedtuple
Cmd = namedtuple('Cmd', 're action')
cmds = [
    Cmd(re='Follow (?P<name>[a-z]+)', action=follow),
)
# etc.
相关问题