[Tutor] Generator expressions...

Modulok modulok at gmail.com
Sun Feb 27 22:34:40 CET 2011


List,

I was messing around with generator expressions. I tried to make a
script that would read a few bytes from '/dev/urandom' for eternity.
It then did something pointless like computing checksums and printing
them out. Unfortunately, the script only runs a few seconds and then
terminates. I'm not sure why.  I tried running it on /dev/zero as well
with the same result; The process terminates, albeit normally. (Exit
status 0. It's not being killed by the kernel or anything.) I was
expecting it to run forever. Below is my code:

## Begin code
#!/usr/bin/env python

# This script will only work on UNIX flavors with a /dev/urandom
#
# It reads from /dev/urandom for eternity, or until you press 'ctrl+c' to
# interrupt it. It computes the hashes forever.
# The point being illustrated is that its memory usage is about constant,
# despite an infinitely large file being read.

import hashlib

fd = open('/dev/urandom', 'rb')
gen = (hashlib.sha256(i).hexdigest() for i in fd.read(4096))

try:
    for i in gen:
        print i     #<-- This loop should never end... but does. Why?

except KeyboardInterrupt:
    gen.close()
    fd.close()
    print "\nBye!"

## End code

I've got to be missing something obvious.
-Modulok-


More information about the Tutor mailing list