Reading an exact number of characters from input

Scott David Daniels Scott.Daniels at Acm.Org
Thu Apr 16 18:27:43 CEST 2009


Paddy O'Loughlin wrote:
> Hi,
> How would I use python to simply read a specific number of characters
> from standard input?
> 
> raw_input() only returns when the user inputs a new line (or some
> other special character).
> I tried
>>>> import sys
>>>> sys.stdin.read(15)
> 
> and that *returns* up to 15 characters, but it keeps accepting input
> (and doesn't return) until I press Enter.
> 
> My initial thoughts are that a function like C's fgetc would be the
> easiest way to do it, but I haven't been able to find an equivalent in
> my google search, so I was wondering if anyone here might have some
> ideas.

Terminal I/O via stdin is often line buffered, and for very good
reasons.  If, after executing sys.stdin.read(15) I typed 20 "A"s,
then 19 backspaces, then 19 "a"s, what would you want the result to be?
Now that you've answered that, how would a system that provided
you that behavior allow the other answer to someone who wanted
the opposite.

sys.stdin is not a keyboard driver.

--Scott David Daniels
Scott.Daniels at Acm.Org



More information about the Python-list mailing list