stdin: processing characters

Kevin Simmons kps at sent.com
Mon May 1 03:01:35 EDT 2006


Serge Orlov wrote:
> Cameron Laird wrote:
>> In article <2Bd4g.21380$tN3.16246 at newssvr27.news.prodigy.net>,
>> Edward Elliott  <nobody at 127.0.0.1> wrote:
>>> Kevin Simmons wrote:
>>>> I have a python script that prompts the user for input from stdin via a
>>>> menu. I want to process that input when the user types in two characters
>>>> and not have to have the user press <CR>. As a comparison, in the bash
>>>> shell one can use (read -n 2 -p "-->" CHOICE; case $CHOICE in...). Works
>>>> great and is very
>>> I did something like this a couple years ago, curses was the easiest way I
>>> found to do it.  It's pretty painless with the wrapper function, which
>>> restores your terminal on error/exit.
>>>
>> Kevin, the bad news is that curses() is as good as Python gets in
>> this regard.  For better or worse, to the best of my knowledge,
>> unextended Python caNOT implement bash's read.  Here's the closest
>> small approximation I know:
>>
>>   import curses
>>   import os
>>
>>   msvcrt = curses.initscr()
>>   msvcrt.addstr("-->")
>>   first = msvcrt.getch()
>>   second = msvcrt.getch()
>>   os.system("stty echo -nl")
>>   print "\nThe two characters are '%s' and '%s'." % (first, second)
>>
>> I hope someone proves me wrong.
> 
> I'm not sure what "unextended Python" means, but on POSIX platforms
> termios module can disable echo and command line option -u can disable
> buffering. I think there should be a way to disable buffering after
> program started. Probably fcntl module.
> 
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()

Thanks again,
Kevin



More information about the Python-list mailing list