reading piped input in Windows

Bengt Richter bokr at oz.net
Sat Nov 15 14:30:42 EST 2003


On Sat, 15 Nov 2003 18:27:22 +0100, Patrick Useldinger <p at trick.lu> wrote:

>Hi,
>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?
>
Some versions of windows have a bug in i/o redirection for programs started
via data/script file extension association (if you have perl on your machine
you will have the same problem piping to/from perl scripts started by extension association).
It is probable that running the interpreter directly would make it work, e.g.,

    python t1.py | python t2.py

But you probably want to spell it t1|t2. On windows, t1 and t2 will have to be
executables to do that reliably across windows versions. Executables are generally
associated with the usual extensions .exe, .com, .bat, and .cmd, so one way to
solve the spelling problem is to provide a t1.bat or t1.cmd that runs python
explicitly with t1.py as arg, as you would do it from the command line, e.g.,
a t1.cmd whose single line content is

    @python <absolute directory path to your script>t1.py

This will be slower than also supplying the absolute path to python, but you won't
have to change it when you upgrade and python winds up in c:\python24 instead of c:\python23.
OTOH, if you need a specific version of python to interpret your script, supplying the full
path will lock it in.

Note that a .bat or .cmd invocation of python also gives you the opportunity to pass a
command line option, e.g., python -u drive:\your\path\t1.py to run with unbuffered binary
stdout and stderr.

Regards,
Bengt Richter




More information about the Python-list mailing list