I've been doing some internal automation which is basically turning a workflow that Evelyn regularly does into a script that takes care of most of the "light manual labor", so she can concentrate on the higher value part of that work. Part of this involves prompting about what to do next...
One of the first libraries I wrote in Python back in 1997 when I started using it was a port of a previous C library I had which would set the terminal in raw mode and read a response to a prompt. I decided to put this on steroids and make the task a bit easier. Martin Blais has made hos if this code in his SVN helper, for example. Read on for more information...
My use case is for getting user response to questions like the following:
What now: E)dit S)end Q)uit? [Esq] Are you sure you want to quit? [Y/n]
Where '[Esq]' indicates to the user that valid choices are e, s, and q, with e being the default. So, I could tell the library that choices='esq' and default='e', but why not have it figure that out if my string ends with '[Esq]' or '[Y/n]'? Take it a step further and if it sees 'E)dit S)end Q)uit' go ahead and set up the '[Esq]' choice string... You can, of course, override it if you like.
Here's an example:
stdinCtrl = rawstdin.RawStdinClass() while True: # Ask a question, use A)nswer tagging for allowed values and # the first alternative as the default if the user hits ENTER. a = stdinCtrl.hotkey('Menu:\nC)ontinue Q)uit H)ostname U)ptime') if a == 'q': # Ask a question, use [Y/n] markup with capitalized option as # default if the user hits ENTER. if stdinCtrl.hotkey('Really quit? [Y/n] ') == 'y': break if a == 'c': continue if a == 'h': os.system('hostname') if a == 'u': os.system('uptime') # Ask a question, specify that "ynm" are the available choices # with "m" as the default if the user hits ENTER. if stdinCtrl.hotkey('Did you enjoy the demo? [Yes/No/MAYBE] ', 'ynm', 'm') == 'y': print 'Yay!'
It's worth noting that the RawStdinClass sets up an atexit handler which will return the terminal to it's normal mode when the program exits, even if it fails in certain cases. So hopefully this will prevent most cases where the terminal is left in raw mode accidentally.
This code is available currently at ftp://ftp.tummy.com/pub/tummy/python-rawstdin/ If there's demand, I'll look at packaging it up a littler further and getting it into the Cheese Shop.comments powered by Disqus