-2

有没有一种简单的方法可以将带有值的参数添加到python3's cmd.Cmd

例如,使用简单的参数很容易实现命令:

> action1 param1 param2

通过添加do_action1()andcomplete_action1()来完成,我可以搜索现有参数的列表。

但是您将如何使用值实现参数,例如:

> action1 param1=234 param2=SomeTextValue

或者

> action1 param1 234 param2 SomeTextValue

whereparam1将设置为234和。param2SomeTextValue

这可以解析cmd.Cmd吗?

我只能考虑获取整个参数列表,do_action1( self, params = None )然后自己解析它。

如果我使用optparse参数必须以破折号为前缀-por--param1--param2,所以要完成,cmd.Cmd我必须先输入 2 个破折号...

> action1 --param1=234 --param2=SomeTextValue

如果我必须手动解析参数,是否有任何类似的 python3 模块optparse不希望参数具有 2 个破折号前缀?

有什么建议么?

4

1 回答 1

1

Well, cmd.Cmd doesn't actually do a whole lot of parsing for you, anyway. So, yes, you can handle parameters with arguments simply by completing parameters with a trailing =, and parsing the commands yourself:

import cmd

def parse(arg):
    return tuple(k.partition('=') for k in arg.split())

class MyShell(cmd.Cmd):
    def do_foo(self, arg):
        for x, _, y in parse(arg):
            print(x, y)

    def complete_foo(self, text, line, begidx, endidx):
        # Cmd treats = as the end of params; we don't want that.
        if line.endswith('='):
            return ()

        opts = ['param1=', 'param2', 'param3=']
        return [opt for opt in opts if opt.startswith(text)]

MyShell().cmdloop()

Example usage:

(Cmd) foo param<TAB>
param1=  param2   param3=  
(Cmd) foo param1=a param
param1=  param2   param3=  
(Cmd) foo param1=a param2 param3=ah
param1 a
param2 
param3 ah

Note that our completions contain a trailing = as a hint to the user, to let them know a parameter can be passed.

于 2012-08-28T00:30:19.287 回答