2

So say I have this graph

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

Now what I want to do is something have user interact with this class.. Something like:

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

You know something like this.. (until user presses some secret button to quit)

How do i do this in python Thanks

1
  • Is what you want anything more than the REPL ? Commented Feb 1, 2013 at 10:20

3 Answers 3

4

You want to look at http://docs.python.org/2/library/cmd.html as it handles the processing loop etc.

Dough Hellman http://www.doughellmann.com/PyMOTW/cmd/ is always a great resource of examples.

From Dough

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()

Example

$ python cmd_arguments.py
(Cmd) help

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

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

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

Again all from Dough Hellman :D

Sign up to request clarification or add additional context in comments.

Comments

1

You can do this with raw_input() To quit you have to press Crtl+C

A small sample script:

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()

Comments

1

Very simple python shell-like environment using exec:

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

As a side note, using exec is dangerous, and should be executed only by trusted users. This allows users to run any command they wish on your system.

3 Comments

-1 for even recommending exec when there's stuff like the cmd module in the stdlib. Your 'solution' creates more problems than it solves.
@l4mpi exec is an awful solution when you want to expose API to unauthorized users. However because it seems that the user needs a simple solution for a simple case, and possibly for local uses only, this solution works best.
I don't think he's interested in a local solution - and if he were, starting the script with python -i would be better than your while / exec loop. And while yoour solution is indeed simple, setting up a REPL with cmd is dead simple too, but produces an infinitely better result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.