简体   繁体   English

自定义交互式终端(CLI),具有自动完成的类和对象

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

I would like to have an interactive prompt similar to IPython within a program. 我想在程序中有一个类似于IPython的交互式提示。

The features I would like to have are: 我想拥有的功能是:

  • Custom prompt 自定义提示
  • Auto-completion on object's methods and attributes 自动完成对象的方法和属性
  • Execution of methods, read/write attributes 方法的执行,读/写属性
  • Display docstring on error 出现错误时显示文档字符串

So far I've been playing with readline with an auto-completion callback function and magic methods such as __dir__ , __doc__ or __dict__ . 到目前为止,我一直在玩readline有自动完成回调函数和魔术方法如__dir____doc____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. 一位朋友建议我使用IPython而不是自定义解决方案。 Unfortunately IPython is too open for my application where newbies will get confused for sure. 不幸的是,对于我的应用程序来说,IPython太开放了,新手肯定会感到困惑。 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. 不幸的是,答案建议使用不是我所需要的cmd模块。

Embed IPython . 嵌入IPython Better than making something like IPython, because it is IPython. 比制作​​类似IPython的东西要好,因为它是IPython。

At a minimum, launching an IPython session involves: 至少,启动IPython会话涉及:

from IPython import embed
embed()

There's a lot of additional configuration options available (including examples) in the IPython Reference IPython参考中提供了许多其他配置选项(包括示例)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM