[Tutor] A question about using stdin/out/err vs named files

Alan Gauld alan.gauld at btinternet.com
Sun Oct 19 10:28:01 CEST 2014


On 18/10/14 19:36, George R Goffe wrote:

> When you run a python program, it appears that stdin, stdout, and stderr are opened automatically.

correct.

> I've been trying to find out how you tell if there's data in stdin

Same way you tell if there's data in any file/stream - you read
from it.

In the old days when I programmed in C there were a pair of calls
often used for this: getc() and ungetc(). You read a character
with getc() then pout it back with ungetc(). Unfortunately they
don't exist in Python stdlib. But, there is a getch()/ungetch()
in the msvcrt for Windows, so you could use that. The curses module
on linux has an ungetch() but no getch() - which seems bizarre...

Steven has posted a solution using read(1) but that blocks
so you need to use the isatty() method which all seems a bit
messy and doesn't work with tty input.

On further investigation the curses.screen object has a getch()
method, but its not clear how the curses.ungetch() relates to
that (there's no help() documentation) and I've run out of time to
experiment. But if you need a linux solution that works with
any kind of stdin that might be worth exploring.

Sorry, not a great answer but hopefully its of some use.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.flickr.com/photos/alangauldphotos



More information about the Tutor mailing list