[Tutor] how to check for stdin?

Michael P. Reilly arcege@shore.net
Mon, 5 Feb 2001 10:45:30 -0500 (EST)

> Hi there,
> I would like to check for STDIN in a script. Now there is no
> problem with sys.stdin, if there really is STDIN, but as soon
> as no STDIN is present, python stops and wait for me to enter
> some input. 
> How can i check if there actually _is_ STDIN before i attempt to
> read it?
> christian
> P.S. sorry, if this has been asked before, i did not find anything
> in the web about it.

I doubt that you could check on windoze, but in a UNIX environment
there is knowledge of whether a open file is attached to a terminal or
not.  A method called "isatty()" returns true if associated with a

$ cat eggs.py
import sys
if not sys.stdin.istty(): # redirected from file or pipe
  stdin_data = sys.stdin.read()
  stdin_data = 'not read from stdin'
print `stdin_data`

$ echo toast | python eggs.py
$ python eggs.py
'not read from stdin'


PS: I don't think it has been asked in years actually. ;)

| Michael P. Reilly, Release Manager  | Email: arcege@shore.net        |
| Salem, Mass. USA  01970             |                                |