Weirdness with python and stdin redirection under Win32

Jonathan M. Gilligan jonathan.gilligan at vanderbilt.edu
Tue Dec 3 21:56:31 EST 2002


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"

Consider the following script, which I want to use as a prototype for a
simple stdin --> stdout filter:

    # foo.py
    import sys

    print "fileno = ", sys.stdin.fileno()

    lines = sys.stdin.xreadlines()
    for line in lines:
        sys.stdout.write(line)


On win32 (Win2k pro, SP3), using ActiveState ActivePython 2.2.1 build 222, I
can execute foo.py either by typing "foo.py" or "python foo.py" on the
command line (the relevant registry key for opening .py files has command
'C:\Python22\python.exe "%1" %*').

If I type "echo bar | foo.py", I get

    C:\>echo bar | foo.py
    The process tried to write to a nonexistent pipe.
    fileno =  -1
    Traceback (most recent call last):
      File "C:\foo.py", line 7, in ?
        lines = sys.stdin.readlines()
    IOError: [Errno 9] Bad file descriptor

whereas if I type "echo bar | python foo.py", I get

    C:\>echo bar | python foo.py
    fileno =  0
    bar

Other tests yield:

    C:\>foo.py < foo.py
    fileno =  -1
    Traceback (most recent call last):
      File "C:\Documents and Settings\Jonathan\My Documents\Programming\Omap
VU\Fast
    CameraDriver\BF_LabView\Leo\foo.py", line 7, in ?
        for line in lines:
    IOError: [Errno 9] Bad file descriptor

    C:\>python foo.py < foo.py
    fileno =  0
    # foo.py
    import sys

    print "fileno = ", sys.stdin.fileno()

    lines = sys.stdin.xreadlines()
    for line in lines:
        sys.stdout.write(line)


If I just type "foo.py" or "python foo.py" on the command line, I get
"fileno = 0" in both cases and the script works identically in both cases.

Can anyone explain what's happening? Why the file descriptor for redirected
stdin has a fileno of -1 if the python script is invoked using "foo.py" but
not when it's invoked with "python foo.py"?

Thanks,
Jonathan





More information about the Python-list mailing list