Problems with select() and stdin

Iñigo Serna inigoserna at terra.es
Sun Aug 18 16:30:53 CEST 2002


Hello,

I'm having problems when using select.select() and sys.stdin.

What I want is that the script reads from a file ('test.py' in the
example) unless it receives input from stdin.

***********************************************************************************
Example: test.py
***********************************************************************************

#!/usr/bin/env python

import sys

def read_stdin():
    from select import select

    try:
	# select from stdin with 2 secs. timeout
        fd = select([sys.stdin], [], [], 2)[0][0]
        stdin = ''.join(fd.readlines())[:-1]
#        fd.close()
#        os.close(sys.stdin.fileno)
#        del(fd)
#        sys.stdin = sys.__stdin__
    except IndexError:
        stdin = ''
    return stdin


# main
buf = read_stdin()
if buf == '':
    buf = open('test.py', 'r').readlines()
    buf = ''.join(buf)[:-1]
print '*' * 68
print buf
print '*' * 68

question = raw_input('Question? ')
print question

***********************************************************************************

When I execute the script with no input from stdin it works ok, 

$ ./test.py
[..'test.py' contents...]
Question? _

but if I do something like:

$ ps efax | ./test.py
[...'ps efax' output ...]
Question? Traceback (most recent call last):
  File "./test.py", line 31, in ?
    question = raw_input('Question? ')
EOFError: EOF when reading a line

the script shows the result from 'ps efax', but as sys.stdin is not
closed, 'raw_input' fails because it receives -1 from stdin continuosly.

I've tried to stop the select closing stdin, but nothing I've tried
works:

#        fd.close()
#        os.close(sys.stdin.fileno)
#        del(fd)
#        sys.stdin = sys.__stdin__


How can I close stdin after I get the data I want?

I'm using Python 2.2.1 on Linux 2.4.18.

Thanks in advance,
Iñigo Serna

-------------- next part --------------
A non-text attachment was scrubbed...
Name: signature.asc
Type: application/pgp-signature
Size: 196 bytes
Desc: Esta parte del mensaje esta firmada digitalmente
URL: <http://mail.python.org/pipermail/python-list/attachments/20020818/d6394ad1/attachment.sig>


More information about the Python-list mailing list