0

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.

Thomas
  • 6,515
  • 1
  • 31
  • 47

2 Answers2

1

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>
dim
  • 1,697
  • 2
  • 13
  • 21
  • Good lookin'- thanks. There is the issue of autocompletion, but that's a shell thing I guess - ideally I write wrappers such that I can specify autocompletion behavior once, and it gets used in both situations, but it the autocompletion mechanisms might be too different for this to make sense. – Thomas Jan 13 '11 at 03:39
1

Another thing that you may find useful is cmdln module.

anatoly techtonik
  • 19,847
  • 9
  • 124
  • 140
  • Hm, I'll look into it - I've used cmd2 before, but never cmdln. – Thomas Jan 26 '12 at 18:14
  • I'm confused by the documentation - does this do cmd.py-like things at all (like ftp), or just command line stuff (like git, hg)? – Thomas Jan 26 '12 at 18:19
  • The primary purpose of the tool is to create command line stuff like git, hg. I didn't investigate compatibility with `cmd` module to provide interactive features with the same interface, but it seems natural to have this support there. – anatoly techtonik Jan 27 '12 at 17:51