[Tutor] Stdin email question [sys.stdin is unseekable / try StringIO]

Magnus Lyckå magnus@thinkware.se
Mon May 19 06:16:01 2003


At 23:06 2003-05-18 -0700, Danny Yoo wrote:
>This would work... except that it's 'sys.stdin':  Python itself doesn't
>know how to travel in time!

That's what I thought, and I was just about to write about StringIO,
but then I made a small test, it worked!

[mly@kaunas tmp]$ python r2.py < r2.py
import sys
print sys.stdin.read()
print sys.stdin.tell()
sys.stdin.seek(0)
print sys.stdin.tell()
print sys.stdin.read()


122
0
import sys
print sys.stdin.read()
print sys.stdin.tell()
sys.stdin.seek(0)
print sys.stdin.tell()
print sys.stdin.read()

This works both in Unix and in Win2k. But it obviously depends on
how you pass things in to stdin... (Which isn't so strange if you
think about it. sys.stdin is just a filedescriptor. What's special
isn't the filedescriptor, but what you pass to it. A pipe and a
file is not the same...)

[mly@kaunas tmp]$ cat r2.py | python r2.py
import sys
print sys.stdin.read()
print sys.stdin.tell()
sys.stdin.seek(0)
print sys.stdin.tell()
print sys.stdin.read()


Traceback (most recent call last):
   File "r2.py", line 3, in ?
     print sys.stdin.tell()
IOError: [Errno 29] Illegal seek

In Windows 2000, it's more devious, because there if fails without
any error message:

P:\python\tmp>type r2.py | python r2.py
import sys
print sys.stdin.read()
print sys.stdin.tell()
sys.stdin.seek(0)
print sys.stdin.tell()
print sys.stdin.read()


0
0

I humbly apologize...


--
Magnus Lycka (It's really Lyck&aring;), magnus@thinkware.se
Thinkware AB, Sweden, www.thinkware.se
I code Python ~ The shortest path from thought to working program