Basic misunderstanding of generators

Barak, Ron Ron.Barak at lsi.com
Mon Dec 22 04:47:02 EST 2008


Hi All,

I want to use generators to print lines taken from a gzipped file.
I've never used generators, so probably my problem is basic misunderstanding of generators.

In the below program, I expected the last line ("print line_") to print the first line of the sac.log.gz file.
Instead, I get:

<generator object at 0x00B93A08>

Could you tell me what I'm doing wrong (or point me to a URL that could set me straight) ?

Thanks,
Ron.

$ cat LogManager_try.py
#!/usr/bin/env python
import gzip
import os
class LogStream():
    """
    """

    def __init__(self, filename):
        self.filename = filename
        self.input_file = self.open_file(filename)
    def open_file(self, in_file):
        """
        The gzip module checks if the input file is a gzipped file, only at the read stage.
        This is why the f.readline() is needed.
        """
        try:
            f = gzip.GzipFile(in_file, "r")
            f.readline()
        except IOError:
            f = open(in_file, "r")
            f.readline()
        f.seek(0)
        return(f)
    def next_line(self, in_file):
        """
        """
        for line_ in in_file:
            yield line_.strip()
if __name__ == "__main__":
    filename = "sac.log.gz"
    log_stream = LogStream(filename)
    line_ = log_stream.next_line(log_stream.input_file)
    print line_
$ python LogManager_try.py
<generator object at 0x00B94648>
$

--
Ron Barak, System Development Engineer
LSI Technologies Israel Ltd
63 Bar Yehuda Road, Nesher 36651 Israel
Tel: (+972) 4 8203454 x1542   Fax: (+972) 4 8203464
[cid:263372909 at 22122008-2BEE][cid:263372909 at 22122008-2BF5]


Remember, Ginger Rogers did everything Fred Astaire did, but backwards and in high heels. (Faith Whittlesey)


-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20081222/4ac11393/attachment.html>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: image001.jpg
Type: image/jpeg
Size: 1512 bytes
Desc: image001.jpg
URL: <http://mail.python.org/pipermail/python-list/attachments/20081222/4ac11393/attachment.jpg>
-------------- next part --------------
A non-text attachment was scrubbed...
Name: image003.jpg
Type: image/jpeg
Size: 1650 bytes
Desc: image003.jpg
URL: <http://mail.python.org/pipermail/python-list/attachments/20081222/4ac11393/attachment-0001.jpg>


More information about the Python-list mailing list