2

だから私はこのグラフを持っているとしましょう

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

あなたはこのようなことを知っています..(ユーザーが秘密のボタンを押して終了するまで)

Pythonでこれを行うにはどうすればよいですか ありがとう

4

3 に答える 3

4

処理ループなどを処理するため、 http://docs.python.org/2/library/cmd.htmlを参照してください。

Dough Hellman 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

于 2013-02-01T10:25:57.900 に答える
1

を使用した非常に単純な python シェルのような環境exec:

cmd = raw_input("> ")
while cmd:
    try:
        exec(cmd)
    except Exception, e:
        print str(e)
    cmd = raw_input("> ")

補足として、使用execは危険です。信頼できるユーザーのみが実行する必要があります。これにより、ユーザーはシステム上で任意のコマンドを実行できます。

于 2013-02-01T10:22:35.580 に答える
1

これは raw_input() で実行できます。終了するには、Crtl+C を押す必要があります

小さなサンプル スクリプト:

import readline # allows use of arrow keys (up/down) in raw_input()

# Main function
def main():
  # endless command loop
  while True:
    try:
      command = raw_input('$ ')
    except KeyboardInterrupt:
      print   # end programm with new line
      exit()

    parseCommand(command)

def parseCommand(command):
  print 'not implemented yet'

if (__name__ == '__main__'):
  main()
于 2013-02-01T10:24:06.517 に答える