Reading twice from STDIN
Hans Mulder
hansmu at xs4all.nl
Fri Dec 2 08:04:42 EST 2011
On 2/12/11 10:09:17, janedenone wrote:
> I had tried
>
> sys.stdin = open('/dev/tty', 'r')
That seems to work for me. This code:
import sys
if sys.version_info.major == 2:
input = raw_input
for tp in enumerate(sys.stdin):
print("%d: %s" % tp)
sys.stdin = open('/dev/tty', 'r')
answer = input('What is the carrying capacity of a swallow? ')
print("You answered: %s" % answer)
print("File descriptor is %d" % sys.stdin.fileno())
... does what I expect it to do in both Python 2.7 and Python 3.2.
> but the actual solution is slightly more complicated. With your help
> (and another round of Google searches), I found exactly what I was
> looking for:
>
> http://turambar.org/jarkko/stdin_input.php
>
> Because raw_input() (input() in Python 3) reads from file descriptor
> 0, the solution is to copy this file descriptor elsewhere, and use a
> file descriptor pointing to /dev/tty for the user input.
That's odd. For some reason, I can get away with a simple
sys.stdin = open('/dev/tty')
and raw_input will merrily read from file descriptor 3.
I'm using Pyhton 2.7.1 and 3.2 on MacOS/X 10.5.0.
What version are you using?
-- HansM
More information about the Python-list
mailing list