pythonpython-interactiveinteractive-shell

Custom interactive terminal (CLI) with autocompletion on classes and objects


I would like to have an interactive prompt similar to IPython within a program.

The features I would like to have are:

So far I've been playing with readline with an auto-completion callback function and magic methods such as __dir__, __doc__ or __dict__.

I am sure I can implement such solution, but I am looking for an existing module that can do the job for me.

In my idea I would like to use it like this:

class Foo:
    def Say(self): 
        return "The answer is 42"
foo = Foo()

cli = Cli() # The terminal interface I want to have
cli.RegisterObject(foo, showAttributes = True, showProtected = True)
cli.AddCommand('exit', exit)
cli.Start(defaultPrompt = ">")

A friend advised me to use IPython instead of a custom solution. Unfortunately IPython is too open for my application where newbies will get confused for sure. I don't want the final user to have access to everything.

At the end we will have something like this:

$ ./cli.py
>foo.<tab>
Say
>foo.Say()
The answer is 42
>bar.AreYouHere()
Unknown command!
>exit

Some related questions are:

Unfortunately the answers advise to use cmd module which is not very much what I need.


Solution

  • Embed IPython. Better than making something like IPython, because it is IPython.

    At a minimum, launching an IPython session involves:

    from IPython import embed
    embed()
    

    There's a lot of additional configuration options available (including examples) in the IPython Reference