Pergunta

I have an command line interpreter (or "line-oriented command interpreter" in the python docs for the cmd module) for a program that I'd like to add command line utility interface to.

For example, now a session looks like this: (% for shell prompt, :) is my custom prompt)
% tasks (invokes command line interpreter)
:) clockHours Teaching_Sara_to_coregister_T1_to_T2
:) exit

In addition, I want this interface:
% tasks clockHours Teaching_Sara_to_coregister_T1_to_T2

I envision custom interpreter commands mapped onto subcommands in the command line utility. Does there exist a library for doing these together? It would be great not to have to write completion code twice, command structure code twice, etc. If not, any advice for me if I try to implement this behavior, or thoughts on how useful it might be?

Obviously I lose the advantage of simple temporary variables, which is why I was using the interpreter approach to begin with, but many of my custom interpreter commands do not rely on this behavior, or could be easily modified not to require it - it is that subset that I want command line utility subcommands for.

Foi útil?

Solução

cmd module may be enough for what you want if I correctly understand your problem.

Your final solution may be close to below example:

import cmd
import sys

class MyCmd(cmd.Cmd):
    def do_hello(self, line):
        print "hello"
    def do_exit(self, line):
        return True

if __name__ == '__main__':
    my_cmd = MyCmd()

    if len(sys.argv) > 1:
        my_cmd.onecmd(' '.join(sys.argv[1:]))
    else:
        my_cmd.cmdloop()

giving this behavior:

C:\_work\home>jython cmdsample.py hello
hello

C:\_work\home>jython cmdsample.py
(Cmd) hello
hello
(Cmd) exit

C:\_work\home>

Outras dicas

Another thing that you may find useful is cmdln module.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top