stdin: processing characters

Serge Orlov Serge.Orlov at gmail.com
Mon May 1 14:32:57 CEST 2006


Kevin Simmons wrote:
> Thanks for your input. I found an answer that suits my needs, not curses
> :-), but stty settings and sys.stdin.read(n) :
>
>   import os, sys
>
>   while 1:
>       os.system("stty -icanon min 1 time 0")
>       print """
>   Radio computer control program.
>   ------------------------------
>   Choose a function:
>      po) Power toggle
>      fq) Change frequency
>      cm) Change mode
>      vo) Change volume
>      re) Reset
>      qu) Quit
>   -->""",
>       func = sys.stdin.read(2)
>       if func == "po":
>           ...
>       ... rest of menu actions ...
>       elif func = "qu":
>           os.system("stty cooked")
>           sys.exit()
>

Looks reasonable if you don't need portability. But you may want to
refactor it a little bit to make sure terminal setting are always
restored:

try:
    do_all_the_work()
finally:
    os.system("stty cooked")

P.S. Maybe its me, but when I see call sys.exit() I always have a gut
feeling this function never returns. But in fact my I'm wrong and
sys.exit is more reasonable: it raises exception. So you can call
sys.exit() inside do_all_the_work and you can still be sure that
os.system("stty cooked") is always executed at the end.




More information about the Python-list mailing list