python - 在 python 中提供命令/shell 类型的交互

标签 python

假设我有这张图

class Graph:
    def __init__(self):
        self.nodes =[]
        self.edges = {}

    def add_node(self,value):
        self.nodes.append(value)

    def is_node_present(self,node):
        return True if node in self.nodes else False

现在我想做的是让用户与这个类进行交互。 像这样的东西:

> g = Graph()
 query executed
> g.add_node(2)
  query executed
>g.is_node_present(2)
  True

你知道这样的事情..(直到用户按下一些 secret 按钮退出)

我如何在 python 中执行此操作 谢谢

最佳答案

你想看http://docs.python.org/2/library/cmd.html因为它处理处理循环等。

面团赫尔曼 http://www.doughellmann.com/PyMOTW/cmd/始终是示例的重要资源。

来自面团

import cmd

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

    def do_greet(self, person):
        """greet [person]
        Greet the named person"""
        if person:
            print "hi,", person
        else:
            print 'hi'

    def do_EOF(self, line):
        return True

    def postloop(self):
        print

if __name__ == '__main__':
    HelloWorld().cmdloop()

例子

$ python cmd_arguments.py
(Cmd) help

Documented commands (type help ):
========================================
greet

Undocumented commands:
======================
EOF  help

(Cmd) help greet
greet [person]
        Greet the named person

同样来自 Dough Hellman :D

关于python - 在 python 中提供命令/shell 类型的交互,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14644061/

相关文章:

带掩码的 Python OpenCV matchTemplate - 在所有位置找到匹配项

python - 有条件地连接 Pandas 数据框中的字符串

python - 在 python 中使用 "temporary files"文件夹

python - Pandas 数据操作 : mapping a column with some predetermined values

python替代解决方案scipy空间距离,当前解决方案返回MemoryError

python - Pandas applymap 函数在应用于太多列时会删除行吗?

python列表将每个值相乘

python - 在数学运算中将结果整数转换为具有五位小数的 float

python - 196 算法,函数中有可选输入

python - pylab.show() 忘记了之前的图