模拟CLI壳牌与蟒蛇(Simulating CLI Shell with python)

2019-09-19 13:04发布

我被要求模拟CLI与Python。

这是我做过什么

def somefunction(a,b):
    //codes here
//consider some other functions too

print "--- StackOverFlow Shell ---"
while True:
    user_input = raw_input("#> ")
    splitit = user_input.split(" ")
    if splitit[0] == "add":
        firstNum = splitit[1]
        sNum = splitit[2]
        result = somefunction(firstNum, sNum)
        print result
    //consider some other elif blocks with "sub", "div", etc
    else:
        print "Invalid Command"

我还检查列表的长度,这里的“splitit”我将只允许3变元的,首先将是操作,以及第二和第三是与一些功能将被执行的参数,如果该参数是多3,对于我真的把一张支票。

虽然不知怎的,我设法使它工作,但有没有更好的方法来达到同样的?

Answer 1:

使用Python CMD模块:

检查下面的页面给出几个例子

http://docs.python.org/library/cmd.html为面向行的命令解释器#支持

http://www.doughellmann.com/PyMOTW/cmd - #创建面向行的命令处理器

prompt可以被设置为一个串中的每个用户被要求接受一个新命令时被打印。

intro是“欢迎”信息在节目的开始打印。

例如:

import cmd

class HelloWorld(cmd.Cmd):
    """Simple command processor example."""

    prompt = 'prompt: '
    intro = "Simple command processor example."


Answer 2:

你应该检查出VTE lib目录下:

http://earobinson.wordpress.com/2007/09/10/python-vteterminal-example/

它的作品真的很好,你可以非常轻松地定制它的外观。 这是多么简单:

    # make terminal
    terminal = vte.Terminal()
    terminal.connect ("child-exited", lambda term: gtk.main_quit())
    terminal.fork_command()

    # put the terminal in a scrollable window
    terminal_window = gtk.ScrolledWindow()
    terminal_window.set_policy(gtk.POLICY_AUTOMATIC, gtk.POLICY_AUTOMATIC)
    terminal_window.add(terminal)


文章来源: Simulating CLI Shell with python