[Tutor] Simple question on creating a filter

Bill Mill bill.mill at gmail.com
Fri Feb 11 15:38:01 CET 2005


On Fri, 11 Feb 2005 09:28:35 -0500, Smith, Jeff <jsmith at medplus.com> wrote:
> I'm sorry to both with such a simple question but I've looked in the
> normal places and don't see the quick and dirty answer I know must
> exist.
> 

No worries; that's what this list is for.

> I want to write a simple line selection filter that could be used like:
> 
> filter < file
> 
> In Perl I would do:
> 
> while (<>)
> {
>         print if line meets selection criteria;
> }
> 
> I've tried what I thought would be the Python equivalent but it doesn't
> work:
> 
> for line in sys.stdin:
>         if line meets selection criteria:
>                 print line
> 
> I get the following at runtime:
> 
> Traceback (most recent call last):
>   File "U:\TimeKeeper\mine.py", line 2, in ?
>     for line in sys.stdin:
> IOError: [Errno 9] Bad file descriptor
> 

I'm not quite sure how you're getting that "bad file dscriptor" error.
My code, also on windows (and cygwin) with python2.4:

/d/code/python$ cat test.py
import sys
for line in sys.stdin:
    if line.startswith('a'):
        print line.strip()

/d/code/python$ cat test_in
aline1
bline2
aline3
cline4

/d/code/python$ python test.py < test_in
aline1
aline3

Try to run it like I did, and let me know if it gives you the same
thing; that'll give us a common point of reference.

Peace
Bll Mill
bill.mill at gmail.com

> This is with Python 2.4 on Windows.
> 
> Jeff
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>


More information about the Tutor mailing list