frazman
frazman

Reputation: 33213

giving a command/shell type interaction in python

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

Upvotes: 2

Views: 194

Answers (3)

iTayb
iTayb

Reputation: 12743

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.

Upvotes: 1

sotapme
sotapme

Reputation: 4903

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

Upvotes: 4

tripplet
tripplet

Reputation: 335

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

Upvotes: 1

Related Questions