Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can I insert deletable characters in python input buffer?

Tags:

python

I want to automatically indent the next line of a console app but the user needs to be able to remove it. sys.stdout.write and print make undeletable characters and I can't write to sys.stdin (as far as I know). I'm essentially trying to get smart indenting but I can only nest deeper and deeper. Any ideas on how to climb back out?

Edit: I should have noted that this is part of a Windows program that uses IronPython. While I could do something much fancier (and might in the future), I am hoping to quickly get a reasonably pleasant experience with very little effort as a starting point.

like image 737
Pat Corwin Avatar asked Nov 06 '12 03:11

Pat Corwin


1 Answers

The cmd module provides a very simple interface for creating a command line interface to your program. It might not be able to put some buffer characters in front of the next line but if you're looking for an obvious way to let your users know that the command has returned, it can provide a shell-like prompt at the beginning of each line. If you already have functions defined for your program, integrating them into a processor would be a matter of writing a handler that access the function:

import cmd
import math

def findHpyot(length, height):
    return math.sqrt(length **2 + height **2)

class MathProcessor(cmd.Cmd):
    prompt = "Math>"

    def do_hypot(self, line):
        x = raw_input("Length:")
        y = raw_input("Height:")
        if x and y:
            try:
                hypot = findHypot(float(x), float(y))
                print "Hypot:: %.2f" %hypot
            except ValueError:
                print "Length and Height must be numbers"

    def do_EOF(self, line):
        return True

    def do_exit(self, line):
        return True

    def do_quit(self, line):
        return True

if __name__ == "__main__":
    cmdProcessor = MathProcessor()
    cmdProcessor.cmdloop()

Things to consider when writing an interactive shell using cmd

  1. The name after do_ is the command that your users will use so that in this example, the available commands will be hypot, exit, quit, and help.
  2. Without overriding do_help, calling help will give you a list of available commands
  3. Any call that you want to quit the program should return True
  4. If you want to process entries from the function call, say you wanted to be able to handle a call like "hypot 3 4" you can use the local line variable in the function call
like image 80
sid16rgt Avatar answered Sep 25 '22 13:09

sid16rgt