Re: setting <stdin> to RAW mode???

Guido.van.Rossum@cwi.nl
Wed, 10 Feb 1993 10:18:21 +0100

>Does anyone know of a quick easy way to set sys.stdin to be in
>RAW mode? (non-buffered, etc)
>I would like to be able to call sys.stdin.read(1) and have it
>return when it really reads 1 char and only 1 char WITHOUT echo...

Well, you could always try something along the lines of

import os
sts = os.system('stty raw')
if sts: print '"stty raw" failed, exit status', sts

There's also the optional ioctl module, but I wouldn't call it quick
and easy, and I have no examples at hand. It is also (even) less
portable to use...

Note that you should probably use "try...finally" to make sure that
the tty status is reset to normal when the program exits, even if it
crashes, otherwise your shell finds itself in raw mode. If you are
using System V or a derivative, or even SunOS, you can use code like
this:

import os
saved_tty_state = os.popen('stty -g', 'r').read()
try:
sts = os.system('stty raw')
...
...code using raw mode goes here
...
finally:
sts = os.system('stty ' + saved_tty_state)

The 'stty -g' command returns a string that compactly encodes all tty
settings; passing this string as an argument back to stty restores
these tty settings exactly.

The "finally" clause gets executed even if your code hits an
exception, but it does not prevent a stack trace (unlike "except",
which lets your program continue normally).

--Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl>