reading piped input in Windows
Michael Geary
Mike at DeleteThis.Geary.com
Sat Nov 15 13:57:35 EST 2003
Patrick Useldinger:
> I am writing a filter, i.e. a program that reads from stdin and writes
> to stdout. It works ok when run on its own, but does not work when I try
> to use another program's output.
>
> - The producer program (t1):
> print "a b c"
> print "d e f"
>
> - The filter program (t2):
> import sys
> r = sys.stdin.readlines()
> for i in r:
> print '<',i,'>'
>
> When i connect them using 't1 ¦ t2', I get the following error message:
> Traceback (most recent call last):
> File "[...]", line 2, in ?
> r = sys.stdin.readlines()
> IOError: [Errno 9] Bad file descriptor
>
> The same programs work correctly under Linux, so I suppose that Windows
> handles redirectionned input differently from 'normal' console input.
> Can anyone point me to a portable solution that works both under Windows
> and Linux?
It works OK for me on Windows XP SP1 with Python 2.3.2:
C:\Test\PythonTest >>t1.py | t2.py
< a b c
>
< d e f
>
What versions of Windows and Python are you running?
BTW, here's a simpler way to write the loop in t2.py:
import sys
for line in sys.stdin:
print '<', line, '>'
Or this, to get rid of the extra newlines (not clear if those are intended
or not):
import sys
for line in sys.stdin:
print '<', line[:-1], '>'
-Mike
More information about the Python-list
mailing list