Weirdness with python and stdin redirection under Win32

Bengt Richter bokr at oz.net
Wed Dec 4 00:24:54 EST 2002


On Tue, 3 Dec 2002 20:56:31 -0600, "Jonathan M. Gilligan" <jonathan.gilligan at vanderbilt.edu> wrote:

>I am getting an error reading stdin only when I invoke a python script by
>typing "bar | foo.py" or "foo.py < bar", but not when typing "bar | python
>foo.py" or "python foo.py < bar". The error arises ecause when input is
>redirected, stdin has fileno = -1 if the script is invoked as "foo.py", but
>correctly has fileno = 0 if it is invoked as "python foo.py"
>
[...]

You have bumped into a well-known bug present in many but not all versions
of windows.

A number of versions of windows do not correctly set up for redirected i/o
when a script is run based on running an interpreter selected by automatic
association via the script's file extension. This will affect e.g., perl also.

The workaround is to invoke the interpreter explicitly, as in python foo.py
(as you did) or to put that in a .cmd or .bat file and then use that file
as the executable, and redirect i/o wrt to that. There are also a couple
of tricky ways you can put a single batch command line as the first line
of your python source, and giving it a .cmd extension, and being able to
get the python part interpreted by python and the whole to do redirection ok.
I'm not sure whether/how a .pyc file may get generated and used that way though.
Maybe it works.

There should be a FAQ by now, I would think.

Regards,
Bengt Richter



More information about the Python-list mailing list