Should "open(sys.stdin)" and "open(file, 'r')" be equivalent?

Simon Mullis simon at
Thu Feb 5 07:37:54 EST 2009

Hi Chris

2009/2/5 Chris Rebert <clp2 at>
> I'd add some print()s in the above loop (and also the 'for f in files'
> loop) to make sure the part of the code you didn't want to share ("do
> stuff with the line") works correctly, and that nothing is improperly
> looping in some unexpected way.

The point is that even with the very, very simple script I posted
above the behavior of open(sys.stdin) and open(filename, 'r') is

The object foo (where foo = sys.stdin) allows me to iterate then hands
back after the loop is finished.

The object bar (where bar = open(filename, 'r')) does not.

Both foo and bar have the same type, methods, repr etc.

> Also, there are several series of lines with invalid indentation;
> could be an email artifact or could be the cause of your problem. If
> the print()s don't yield any useful insight, repost the code again
> with absolutely correct indentation.

(code posted again to fix indents)
#!/usr/bin/env python

import glob, os, sys

class TestParse(object):
    def __init__(self):
        if options.stdin:
            if options.glob:
                self.files = glob.glob(options.glob)
                for f in files:
                    fh = open(f, 'r')

    def scan_data(self,fileobject):
        i = 0
        for line in fileobject:
            print i
            i += 1
            # do stuff with the line...
        print "finished file"

def main():
    T = TestParse()

if __name__ == "__main__":
    from optparse import OptionParser
    p = OptionParser(__doc__, version="testing 1 2 3")
    p.add_option("--glob", dest="glob")
    p.add_option("--stdin", dest="stdin", action="store_true", default="False")
    (options, args) = p.parse_args()

(The code I'm actually using is much more complex than this. I tried
to create the most simple example of it _not_ working as expected...)

> Finally, some stylistic points:
> - don't do 'if (foo):'   use the less noisy 'if foo:' instead
> - don't do 'i = int()'   use the more obvious 'i = 0' instead

My question again, to be more explicit: Should the objects created by
sys.stdin and open(filename, 'r') have the same behavior when iterated
over? They both have __iter__ methods....

Thanks in advance for any suggestions


More information about the Python-list mailing list